Search code examples
phparraysarray-multisort

Array Multisort with a multidirectional array


This one is baffling me at the moment, and I'm a little confused as to what it is doing.

So I have a multi directional array:

$h_info[69993] = array('price' => '1.00', 'url' => 'url', 'rating' => '4');
$h_info[85398] = array('price' => '3.00', 'url' => 'url', 'rating' => '2');
$h_info[34394] = array('price' => '9.00', 'url' => 'url', 'rating' => '0');

Now I have the following while loop

foreach ($h_info as $row) {
      foreach ($row as $key => $value){
        ${$key}[]  = $value; //Creates $price, $url... arrays.
      }  
    }
array_multisort($price, SORT_ASC, $h_info);

Now this works, but it removes the $h_info id from the array and outputs

Array
(
[0] => Array
    (
        [price] => 39
        [url] => url,
        [rating] => 4.5
    )
...

But i need the ID to stay - when I do this:

foreach ($h_info as $row => $id) {
      foreach ($row as $key => $value){
        ${$key}[]  = $value; //Creates $price, $url... arrays.
      }  
    }
array_multisort($price, SORT_ASC, $h_info);

The sort no longer works, but outputs the array correctly:

Array
(
[69993] => Array
    (
        [price] => 39
        [url] => url,
        [rating] => 4.5
    )
...

Solution

  • Try this

    $h_info[69993] = array('price' => '1.00', 'url' => 'url', 'rating' => '4');
    $h_info[85398] = array('price' => '3.00', 'url' => 'url', 'rating' => '2');
    $h_info[34394] = array('price' => '9.00', 'url' => 'url', 'rating' => '0');
    //intitalize array
    $result = array(); // or $result = [];
    //add your main key into "key" parameter of array
    array_walk($h_info, function (&$value,$key) use (&$result) {
        $arr_info = $value;
        $arr_info['key'] = $key;
        $result[] = $arr_info;
    
    });
    //sort in ascending order by price
    usort($result, function($a, $b) {
        if($a['price']==$b['price']) return 0;
        return $b['price'] < $a['price']?1:-1; //  return $a['price'] < $b['price']?1:-1;(note : if you need it in descending order)
    });
    
    echo "<pre>";
    print_r($result);
    ?>
    

    and you will get result like this

        Array
    (
        [0] => Array
            (
                [price] => 1.00
                [url] => url
                [rating] => 4
                [key] => 69993
            )
    
        [1] => Array
            (
                [price] => 3.00
                [url] => url
                [rating] => 2
                [key] => 85398
            )
    
        [2] => Array
            (
                [price] => 9.00
                [url] => url
                [rating] => 0
                [key] => 34394
            )
    
    )
    

    in ascending order by price if you need to know more information abouta array_walk() and usort() please check this links : http://php.net/manual/en/function.array-walk.php http://php.net/manual/en/function.usort.php