简体   繁体   中英

Find the key for lowest number in 2d array

I need to find the lowest, 2nd lowest,.... price in a 2d array. I have an array, $items, which looks like this:

Array
(
    [0] => Array
        (
            [item] => item1
            [price] => 5.00
        )

    [1] => Array
        (
            [item] => item2
            [price] => 10.00
        )
    [2] => Array
        (
            [item] => item3
            [price] => 5.00
        )
    ........
)
  1. total array divided by 2, than floor.
  2. if floor is 1, than find the lowest price(5.00) array (return 0 or 2).
  3. if floor is 2, than find the lowest and 2nd lowest price (because there're 2 same price 5.00, so return (0 and 2)
  4. if floor is 3, than find the 1st, 2nd, 3rd lowest array (return 0 and 2 and?)

To sort an array with whatever way you want and if that array is not an indexed array but multi-dimentional array, you can always use

usort(array &$array, callable $callback): bool

For example:

usort($user_aray, function($item1, $item2){
    if ($item1['price'] == $item2['price']) {
        return 0;
    }
    return ($item1['price'] < $item2['price']) ? -1 : 1;
}

I am not writing the complete solution to your whole problem because it seems its a problem from an school assignment or programming copetetion which should be solved by you. Try hard, this clue might help you. For more information about usort function you can check: https://www.php.net/manual/de/function.usort.php

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