具有多向数组的 Array Multisort

Array Multisort with a multidirectional 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');

现在我有以下 while 循环

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

现在可以了,但是它会从数组中删除 $h_info id 并输出

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

但我需要保留 ID - 当我这样做时:

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

排序不再有效,但正确输出数组:

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

试试这个

$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);
?>

你会得到这样的结果

    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
        )

)

按价格升序排列 如果您需要了解有关 array_walk() 和 usort() 的更多信息,请查看此链接: http://php.net/manual/en/function.array-walk.php http://php.net/manual/en/function.usort.php