具有多向阵列的Array Multisort

时间:2016-01-20 11:45:30

标签: php arrays array-multisort

此刻此刻令我感到困惑,我对它的作用感到有些困惑。

所以我有一个多向阵列:

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

但我需要留下身份证 - 当我这样做时:

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

1 个答案:

答案 0 :(得分:-1)

试试这个     

$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