在PHP多维数组中使用USORT之后如何添加新密钥

时间:2019-05-23 13:11:02

标签: php php-7

我在该数组中有一个数组,我想按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
        )

)

2 个答案:

答案 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;
}

Demo on 3v4l.org