如果关联数组包含整数键,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 ) )
答案 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);
?>