我有一个像这样的多维数组。
arr[4]=array('name' => 'ab', 'aid' => 1 'qty' => 10);
arr[5]=array('name' => 'ac', 'aid' => 3 'qty' => 15);
arr[3]=array('name' => 'ad', 'aid' => 2 'qty' => 100);
arr[2]=array('name' => 'ae', 'aid' => 2 'qty' => 150);
我需要按照'援助'来对它们进行排序。但不要像这样改变主要指数。
arr[4]=array('name' => 'ab', 'aid' => 1 'qty' => 10);
arr[2]=array('name' => 'ae', 'aid' => 2 'qty' => 150);
arr[3]=array('name' => 'ad', 'aid' => 2 'qty' => 100);
arr[5]=array('name' => 'ac', 'aid' => 3 'qty' => 15);
可能吗?我该怎么办?感谢。
答案 0 :(得分:0)
来自PHP手册
<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>
在这个例子中,我们将按卷递减,升序版。
我们有一个行数组,但是array_multisort()需要一个列数组,所以我们使用下面的代码来获取列,然后执行排序。
<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}
// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>
http://php.net/manual/en/function.array-multisort.php
修改强>
根据您的需要,您要求:
$arr[4]=array('name' => 'ab', 'aid' => 1, 'qty' => 10);
$arr[5]=array('name' => 'ac', 'aid' => 3, 'qty' => 15);
$arr[3]=array('name' => 'ad', 'aid' => 2, 'qty' => 100);
$arr[2]=array('name' => 'ae', 'aid' => 2, 'qty' => 150);
$keyPositions = array();
foreach ($arr as $key => $value) {
$keyPositions[] = $key;
}
foreach ($arr as $key => $row) {
$aid[$key] = $row['aid'];
}
array_multisort($aid, SORT_ASC, $arr);
$sortedArray = array();
foreach ($arr as $key => $value) {
$sortedArray[$keyPositions[$key]] = $value;
}
echo '<pre>';
print_r($sortedArray);
echo '</pre>';
?>