开发者

Merge PHP Array's by values highest

开发者 https://www.devze.com 2023-04-01 21:46 出处:网络
I have these three sub arrays, I would like to make one array that searches through each array for the highest value, and puts its key

I have these three sub arrays, I would like to make one array that searches through each array for the highest value, and puts its key into another array, to create a new array of key/key values

Edit I'm looking through all 0's, then all 1's, then all 2开发者_如何学运维's to find the highest value there. I want to always start with whatever the all time highest number is though, and move on to the smallest as the keys become unavailabl

Input would be this

Array
(
    Array
    (
        [0] => 16 
        [1] => 27 
        [2] => 36 // highest, 2 is now unavailable
    )
    Array
    (
        [0] => 27
        [1] => 13.5  // highest, 1 is now unavailable
        [2] => 9 
    )
    Array
    (
        [0] => 81 // highest, 0 is now unavailable
        [1] => 18
        [2] => 27 
    )
)

Output would be this

Array
(
    [0] => [2]
    [1] => [1]
    [2] => [0]
)


Something along these lines should do it, if I'm getting you right:

$result = array();

foreach ($array as $numbers) {
    $highestKey = null;
    $highestNum = null;

    foreach ($numbers as $key => $value) {
        if ($value > $highestNum && !in_array($key, $result)) {
            list($highestKey, $highestNum) = array($key, $value);
        }
    }

    $result[] = $highestKey;
}


$results = array();
foreach ($array as $value) {
    arsort($value);
    $temp = array();        
    foreach ($value as $subkey => $subval) {
        if (!in_array($subkey, $results))
        $temp[] = $subkey;
    }       
    $results[] = $temp[0];
}   

http://codepad.org/PAVHni6k

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号