使用PHP array_multisort函数对多维关联数组进行排序,其中包含一些整数键

时间:2011-05-07 13:10:53

标签: php multidimensional-array

如果关联数组包含整数键,array_multisort会自动重置它们,所以我正在丢失数据。这是一个小例子。任何解决方案?

$products = array ( '777.777' => array('price' => 10, 'name' => 'a'),
                    '777' => array('price' => 100, 'name' => 'b')
                  );    

$sort_field     = 'price';
$destination    = SORT_ASC;
$sort_array = array();
foreach ($products as $productId => $product) {
    $sort_array[$productId] = $product[$sort_field];
}       
array_multisort($sort_array, $destination, $products);
print_r($products); 
   // Array ( [777.777] => Array ( [price] => 10 [name] => a ) [0] => Array ( [price] => 100 [name] => b ) ) 

1 个答案:

答案 0 :(得分:0)

试试这个

<?php

    $products = array('777.777' => array('price' => 10, 'name' => 'a'),
                    '777' => array('price' => 100, 'name' => 'b')
                  );

    $products = subval_sort($products, 'price');

    function subval_sort($array, $subkey) {

        foreach ($array as $key => $value) {

            $newArray[$key] = $value[$subkey];
        }

        arsort($newArray);

        foreach ($newArray as $key => $value) {

            $finalArray[$key] = $array[$key];
        }

        return $finalArray;
    }

    var_dump($products);

?>

http://codepad.org/VgdGdWyQ