3

I have two arrays namely arr and arr2.

var arr=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}];

var arr2=[{"month":"January","ip":12},{"month":"June","ip":10}];

Is it possible to get array below shown from above two arrays?

result=[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}];

If i use array_merge then i get answer as

result=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192},{"month":"January","ip":12},{"month":"June","ip":10}];
3
  • 1
    This is happening because if keys are numeric, array_merge won't merge but append new data. From PHP manual: If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Commented Aug 9, 2017 at 9:26
  • ok sir. is there any possible chances to get expected answer? Commented Aug 9, 2017 at 9:28
  • Before you merge together using array_merge or better, array_merge_recursive, make sure that your arrays contain non-numerical keys. You can for example set month name as key of month data. Commented Aug 9, 2017 at 9:31

3 Answers 3

2

The first function that comes to mind is array_merge_recursive(), but even if you assign temporary associative keys to the subarrays, you end up with multiple January values in a new deep subarray.

But do not despair, there is another recursive function that can do this job. array_replace_recursive() will successfully merge these multidimensional arrays so long as temporary associative keys are assigned first.

Here is a one-liner that doesn't use foreach() loops or if statements:

Code: (Demo)

$arr=json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]',true);
$arr2=json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]',true);
echo json_encode(array_values(array_replace_recursive(array_column($arr,NULL,'month'),array_column($arr2,NULL,'month'))));

Output:

[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}]

The breakdown:

echo json_encode(  // convert back to json
         array_values(  // remove the temp keys (reindex)
             array_replace_recursive(  // effectively merge/replace elements associatively
                 array_column($arr,NULL,'month'),  // use month as temp keys for each subarray
                 array_column($arr2,NULL,'month')  // use month as temp keys for each subarray
             )
         )
     );
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah... your solution is better in this situation :)
2

You must decode JSON to arrays, manually merge them and again encode it to JSON :)

<?php
$arr = json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]', true);
$arr2 = json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]', true);

$result = [];
foreach ($arr as &$item) {
    if (empty($arr2))
        break;

    foreach ($arr2 as $key => $item2) {
        if ($item['month'] === $item2['month']) {
            $item = array_merge($item, $item2);
            unset($arr2[$key]);
            continue;
        }
    }
}
if (!empty($arr2))
    $arr = array_merge($arr, $arr2);

echo json_encode($arr);

Comments

0

You should write your own function to do that

$res = [];
foreach ($arr as $item) {
    $res[$item['month']] = $item;
}

foreach ($arr2 as $item) {
    $res[$item['month']] = isset($res[$item['month']]) ? array_merge($res[$item['month']], $item) : $item;
}

var_dump($res);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.