我在该数组中有一个数组,我想按ASC
的顺序,之后我要插入新列rank
,然后它的值将像1,2,3一样增加... / p>
我的阵列
$mainArray = [
"key1" => ["name" => "A", "price" => 5],
"key2" => ["name" => "B", "price" => 7],
"key3" => ["name" => "C", "price" => 2],
];
我的代码
usort($mainArray, function($a, $b) {
return $a['price'] <=> $b['price'];
});
echo "<pre>";
print_r($mainArray);
我正在获取输出
Array
(
[0] => Array
(
[name] => C
[price] => 2
)
[1] => Array
(
[name] => A
[price] => 5
)
[2] => Array
(
[name] => B
[price] => 7
)
)
预期产量
Array
(
[0] => Array
(
[name] => C
[price] => 2
[rank] => 1
)
[1] => Array
(
[name] => A
[price] => 5
[rank] => 2
)
[2] => Array
(
[name] => B
[price] => 7
[rank] => 3
)
)
答案 0 :(得分:1)
排序后,使用foreach()
:
$counter =1;
foreach($mainArray as &$mainArr){
$mainArr['rank'] = $counter;
$counter++;
}
输出:-{Working Demo
答案 1 :(得分:1)
由于对数组进行了排序和重新索引,所以rank
值只是键加1。一个foreach循环将执行您想要的操作:
foreach ($mainArray as $k => &$v) {
$v['rank'] = $k + 1;
}