Sort Multi-dimensional Array by sub Array Value?

In this tutorial learn How to sorting multi-dimensional array by value or sub array value, sort multi-dimensional array using a array_multisort() and array_map() function, 

You can sort array with ascending or descending order using SORT_ASC or SORT_DESC also.   


 EXAMPLE 1 : Sort Multi-dimensional array by value of country in this example.



 <?php

$array = Array
(
    0 => Array
        (
            'name' => 'Nakiya',
            'country' => 'USA',
            'id' => 3,
        ),

    1 => Array
        (
           'name' => 'Taylor',
            'country' => 'UK',
            'id' => 2,

        ),

    2 => Array
        (
            'name' => 'Jack',
            'country' => 'France',
            'id' => 1,

        )
);

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

Above tutorial output: (live demo)


 Array
(
    [0] => Array
        (
            [name] => Jack
            [country] => France
            [id] => 1
        )

    [1] => Array
        (
            [name] => Taylor
            [country] => UK
            [id] => 2
        )

    [2] => Array
        (
            [name] => Nakiya
            [country] => USA
            [id] => 3
        )

)
Example 2 : Sort Multi-dimensional array by value of id in this example.

 <?php

$array = Array
(
    0 => Array
        (
            'name' => 'Nakiya',
            'country' => 'USA',
            'id' => 3,
        ),

    1 => Array
        (
           'name' => 'Taylor',
            'country' => 'UK',
            'id' => 2,

        ),

    2 => Array
        (
            'name' => 'Jack',
            'country' => 'France',
            'id' => 1,

        )
);

array_multisort(array_map(function($element) {
      return $element['id'];
  }, $array), SORT_ASC, $array);
  
print_r($array);
above tutorial output: (live demo)

Array
(
    [0] => Array
        (
            [name] => Jack
            [country] => France
            [id] => 1
        )

    [1] => Array
        (
            [name] => Taylor
            [country] => UK
            [id] => 2
        )

    [2] => Array
        (
            [name] => Nakiya
            [country] => USA
            [id] => 3
        )

)


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...