skip to Main Content

I have array Like this

 $array = [
        [
            'project_id' => 1,
            'Client' => [
                ['Name' => 'Franco',
                'Amount' => 1000.00,
                 ],
                 ['Name' => 'Allan',
                'Amount' => 1000.00,
                ],
                ['Name' => 'Booby',
                'Amount' => 1000.00,
                ]
            ],
          
        ],
      
    ];

I use array_multisort and array_map to sort it by Name in descending, I already tried usort but still not working.. Any Help will be Appreciated

array_multisort(
    array_map(
        static function ($element) {
            return $element['Client']['Name'];
        },
        $array
    ),
    SORT_DESC,
    $array
);

return $array;

3

Answers


  1. Here’s a solution using a function I found from php documentation:

    <?php
    
    /*
    
    Question Author: Not a Pro
    Question Answerer: Jacob Mulquin
    Question: Sort Nested Array base on Value in PHP
    URL: https://stackoverflow.com/questions/76419733/sort-nested-array-base-on-value-in-php
    Tags: php, arrays
    
    */
    
    
    // Author: jimpoz at jimpoz dot com
    // URL: https://www.php.net/manual/en/function.array-multisort.php#100534
    function array_orderby()
    {
        $args = func_get_args();
        $data = array_shift($args);
        foreach ($args as $n => $field) {
            if (is_string($field)) {
                $tmp = array();
                foreach ($data as $key => $row)
                    $tmp[$key] = $row[$field];
                $args[$n] = $tmp;
                }
        }
        $args[] = &$data;
        call_user_func_array('array_multisort', $args);
        return array_pop($args);
    }
    
    function sortProjectsByClientName(&$projects)
    {
        foreach ($projects as &$project) {
            $project['Client'] = array_orderby($project['Client'], 'Name', SORT_ASC);
        }
    }
    
    $projects = [
        [
            'project_id' => 1,
            'Client' => [
                ['Name' => 'Franco',
                'Amount' => 1000.00,
                 ],
                 ['Name' => 'Allan',
                'Amount' => 1000.00,
                ],
                ['Name' => 'Booby',
                'Amount' => 1000.00,
                ]
            ],
          
        ],
        [
            'project_id' => 2,
            'Client' => [
                ['Name' => 'Bob',
                'Amount' => 1000.00,
                 ],
                 ['Name' => 'Trevor',
                'Amount' => 1000.00,
                ],
                ['Name' => 'Alice',
                'Amount' => 1000.00,
                ]
            ],
          
        ]
    ];
    
    sortProjectsByClientName($projects);
    var_dump($projects);
    

    Yields:

    array(2) {
      [0]=>
      array(2) {
        ["project_id"]=>
        int(1)
        ["Client"]=>
        array(3) {
          [0]=>
          array(2) {
            ["Name"]=>
            string(5) "Allan"
            ["Amount"]=>
            float(1000)
          }
          [1]=>
          array(2) {
            ["Name"]=>
            string(5) "Booby"
            ["Amount"]=>
            float(1000)
          }
          [2]=>
          array(2) {
            ["Name"]=>
            string(6) "Franco"
            ["Amount"]=>
            float(1000)
          }
        }
      }
      [1]=>
      array(2) {
        ["project_id"]=>
        int(2)
        ["Client"]=>
        array(3) {
          [0]=>
          array(2) {
            ["Name"]=>
            string(5) "Alice"
            ["Amount"]=>
            float(1000)
          }
          [1]=>
          array(2) {
            ["Name"]=>
            string(3) "Bob"
            ["Amount"]=>
            float(1000)
          }
          [2]=>
          array(2) {
            ["Name"]=>
            string(6) "Trevor"
            ["Amount"]=>
            float(1000)
          }
        }
      }
    }
    
    Login or Signup to reply.
  2. Your question is not clear. However from your try what I can understand is you are trying to sort the client array based on ‘Name’. So to achieve this please try the below logic with the same usort.

    $array = [
        [
            'project_id' => 1,
            'Client' => [
                [
                    'Name' => 'Franco',
                    'Amount' => 1000.00,
                ],
                [
                    'Name' => 'Allan',
                    'Amount' => 1000.00,
                ],
                [
                    'Name' => 'Booby',
                    'Amount' => 1000.00,
                ],
            ],
        ],
    ];
    
    usort($array[0]['Client'], function ($a, $b) {
        return strcmp($a['Name'], $b['Name']);
    });
    
    print_r($array);
    
    Login or Signup to reply.
  3. A one liner using array_multisort() and array_column():

    array_multisort( 
        array_column(
            $array[0]['Client'] , 
            'Name' 
            ),
        SORT_DESC, 
        $array[0]['Client']
        );
    

    Output:

    Array(
     [0] => Array(
       [project_id] => 1
       [Client] => Array(
         [0] => Array(
           [Name] => Franco
           [Amount] => 1000
           )
         [1] => Array(
           [Name] => Booby
           [Amount] => 1000
         )
        [2] => Array(
           [Name] => Allan
           [Amount] => 1000
         )
       )
     )
    )
    

    If you have multiple elements in $array that have to be sorted by client, you can use array_walk() around the sort (it’s still a one liner):

    array_walk( 
        $array,
        function (&$a){
            return array_multisort( 
            array_column(
                $a['Client'] , 
                'Name' 
                ),
            SORT_DESC, 
            $a['Client']
            );
        }
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search