Monday 3 September 2018

Fusion PHP 2 arrays with number of different elements, $ keys of one, $ value of another

I want to merge 2 arrays together that have a different number of elements, using the keys from one and the values from another where/if the keys match. The array that contains the desired values may have less elements in it although I would like to retain the resulting empty keys from the original array. For example:

//Array that contains keys I would like to retain
$arr1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
//Array that contains values I'd like to use
$arr2 = array(01=>123, 03=>123, 05=>123, 07=>123, 09=>123, 11=>123);
//The desired result with some valueless elements
$results = array(01=>123, 02, 03=>123, 04, 05=>123, 06, 07=>123, 08, 09=>123, 10, 11=>123, 12);
As you can see the results array retains 12 elements but only applies values to where the keys from the 2 arrays match.
I have tried $results = array_intersect_key($arr1 + $arr2, $arr2); among other PHP functions as well as:
for ($i=1; $i < count($arr1); $i++) {
    if (isset($arr2[$i])) {
        $arr3[] = $arr2[$i];
    } else {
        $arr3[] = $arr1[$i];
    }
}

print_r($arr3);

No luck as yet.
Thanks in advance!

For arrays like this
$arr1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
$arr2 = array(1=>123, 3=>123, 5=>123, 7=>123, 9=>123, 11=>123);

this should work.
foreach ($arr1 as $key) {
    $results[$key] = isset($arr2[$key]) ? $arr2[$key] : null;
}

or using some other PHP functions:
$results = array_replace(array_fill_keys($arr1, null), $arr2);

0 comments:

Post a Comment