PHP : array sort by sub array value

In this tutorial learn how to sort array by sub array value using array_multisort() and array_map() function.
Can sort array ascending(SORT_ASC) or Descending(SORT_DESC) order with Sub Array value.

Pass a array and sub array value

<?php

array_multisort(array_map(function($element) {
      return $element['<sub array value>'];
  }, $array), SORT_ASC, $array);
  

EXAMPLE TUTORIAL


<?php

$array = Array
(
    0 => Array
        (
            'user_id' => 10,
             'id' => 1,
             'Number' => 3,
             'Active' => 1,
             'Updated' => '2010-03-17 15:44:12',
        ),

    1 => Array
        (
            'user_id' => 9,
             'id' => 2,
             'Number' => 2,
             'Active' => 1,
             'Updated' => '2010-03-17 15:44:12',

        ),

    2 => Array
        (
            'user_id' => 8,
             'id' => 3,
             'Number' => 1,
             'Active' => 1,
             'Updated' => '2010-03-17 15:44:12',

        )
);

array_multisort(array_map(function($element) {
      return $element['user_id'];
  }, $array), SORT_ASC, $array);
  
print_r($array);

No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...