6, "5"=> 1 ), ( "2"=> 1, "5"=> 3 ) I want to create a new array with the " /> 6, "5"=> 1 ), ( "2"=> 1, "5"=> 3 ) I want to create a new array with the " /> 6, "5"=> 1 ), ( "2"=> 1, "5"=> 3 ) I want to create a new array with the "/>

create new array from two arrays in php

124 Views Asked by At

I have two arrays with the same keys, but different values.

Example:

(
    "2"=> 6,
    "5"=> 1
),
(
    "2"=> 1,
    "5"=> 3
)

I want to create a new array with the same keys, but replace the highest values like this:

 (
    "2"=> 6,
    "5"=> 3
)

What should I do?

2

There are 2 best solutions below

1
Nick On BEST ANSWER

You need to iterate getting the maximum value for each key, which you can do with a combination of array_keys, array_combine, array_map and array_column:

$keys = array_keys(reset($arr) ?: []);
$res = array_combine(
    $keys,
    array_map(fn ($k) => max(array_column($arr, $k)), $keys)
    );
print_r($res);

Output:

Array
(
    [2] => 6
    [5] => 3
)

Demo on 3v4l.org

For those using PHP prior to 7.4, you can replace the arrow function with

function ($k) use ($arr) { return max(array_column($arr, $k)); }

Note that this code assumes that all the sub-arrays have the same keys or some subset of the keys of the first sub-array.

0
mickmackusa On

Use a nested loop, check if the key is encountered for the first time or if the stored value for that key is less than the current value.

Code: (Demo)

$result = [];
foreach ($array as $row) {
    foreach ($row as $k => $v) {
        if (!isset($result[$k]) || $result[$k] < $v) {
            $result[$k] = $v;
        }
    }
}
var_export($result);

A functional-style script with nested array_reduce() calls isn't nearly as readable. (Demo)

var_export(
    array_reduce(
        $array,
        fn($result, $row) => array_reduce(
            array_keys($row),
            fn($res, $k) => isset($res[$k]) && $res[$k] >= $row[$k]
                ? $res
                : array_replace($res, [$k => $row[$k]]),
            $result
        ),
        []
    )
);