简体   繁体   中英

How add a new a key after using USORT in PHP multidimensional array

I am having one array in that array i want to make ASC order, after that i want insert new column rank then value it will get increase like 1, 2, 3 ...

My Array

$mainArray = [
    "key1" => ["name" => "A", "price" => 5],
    "key2" => ["name" => "B", "price" => 7],
    "key3" => ["name" => "C", "price" => 2],
];

My Code

usort($mainArray, function($a, $b) {
                return $a['price'] <=> $b['price'];
 });
echo "<pre>";
print_r($mainArray);

I am getting output

Array
(
    [0] => Array
        (
            [name] => C
            [price] => 2
        )

    [1] => Array
        (
            [name] => A
            [price] => 5
        )

    [2] => Array
        (
            [name] => B
            [price] => 7
        )

)

Expected output

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
        )

)

Since your array has been sorted and re-indexed, the rank value is simply the key plus 1. A foreach loop will do what you want:

foreach ($mainArray as $k => &$v) {
    $v['rank'] = $k + 1;
}

Demo on 3v4l.org

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM