4

I would like to merge the associative elements from my second array into my first array where the second array's subarray key matches a row's epg_channel_id value.

First array:

[
    [
        'num' => 1,
        'name' => 'name 1',
        'epg_channel_id' => 'ch111',
        'added' => '1505435915',
    ],
    [
        'num' => 2,
        'name' => 'name 2',
        'epg_channel_id' => 'ch222',
        'added' => '1505435915',
    ],
    [
        'num' => 3,
        'name' => 'name 3',
        'epg_channel_id' => 'ch333',
        'added' => '1505435915',
    ],
    [
        'num' => 4,
        'name' => 'name 4',
        'epg_channel_id' => 'ch444',
        'added' => '1505435915'
    ]
]

And the second array:

[
    ['ch000' => 'Um9jayBJbiBSaW8='],
    ['ch111' => 'Um9jayBJbiBSaW8='],
    ['ch222' => 'Um9jayBJbiBSaW8='],
    ['ch333' => 'Um9jayBJbiBSaW8='],
    ['ch444' => 'Um9jayBJbiBSaW8=']
]

Desired output (for one row):

Array
(
  [0] => Array
  (
    [num] => 1
    [name] => name 1
    [epg_channel_id] => ch111
    [added] => 1505435915
    [ch111] => Um9jayBJbiBSaW8= 
  )
  ...
)

I tried array_recursive, array merge and not works.

4
  • You have a two, two dimensional array, and You want merge their elements? Commented Sep 18, 2017 at 4:28
  • 2
    You should use loop Commented Sep 18, 2017 at 4:31
  • Your first array has 4 elements and your second one has 5 elements? Was this a mistake, or does one have more than the other? Commented Sep 18, 2017 at 4:48
  • Will the channel id always be in the same index? For example, is index 0 of array1 guaranteed to have the same channel id as index 0 of array2? Commented Sep 18, 2017 at 4:52

8 Answers 8

2

If the corresponding indexes in both arrays are guaranteed to have the same channel id, this will work quite efficiently. For example, if $array1[0] is guaranteed to have the same channel id as $array2[0] this solution will work nicely:

$combined = [];
foreach($array1 as $key=>$val){
    $combined[$key] = $val + $array2[$key];
}

However, if the corresponding indexes are not guaranteed to have the same channel ids, this solution will not work, and you'll need to use one of the other posted answers.

One last note if you do use this method is that if the arrays are different sizes, you will want the largest one to be $array1. So, just do a comparison to see which has the most elements.

Sign up to request clarification or add additional context in comments.

2 Comments

OP wants to match first array's epg_channel_id with second array key. This will not produce desired result
@B.Desai Yes, after re-reading, you are likely correct. I have added a disclaimer to my answer. :)
1

You have to loop over two arrays to get desired result: as you have to match epg_channel_id of first array to second arrays inner key

$arr1 = Array
 (
 0 => Array
    (
        "num" => 1,
        "name" => "name 1",
        "epg_channel_id" => "ch111",
        "added" => "1505435915",
    ),
1 => Array
    (
        "num" => 2,
        "name" => "name 2",
        "epg_channel_id" => "ch222",
        "added" => "1505435915",
    ),
2 => Array
    (
        "num" => 3,
        "name" => "name 3",
        "epg_channel_id" => "ch333",
        "added" => "1505435915",
    ),
3 => Array
    (
        "num" => 4,
        "name" => "name 4",
        "epg_channel_id" => "ch444",
        "added" => "1505435915",
    ),
);
$arr2 = Array
 (
 0 => Array
    (
        "ch000" => "Um9jayBJbiBSaW8="
    ),
1 => Array
    (
        "ch111" => "Um9jayBJbiBSaW8="
    ),
2 => Array
    (
        "ch222" => "Um9jayBJbiBSaW8="
    ),
3 => Array
    (
        "ch333" => "Um9jayBJbiBSaW8="
    ),
4 => Array
    (
        "ch444" => "Um9jayBJbiBSaW8="
    ),
);
$new_array = array();
foreach($arr1 as $key=>$value)
{
    foreach($arr2 as $key1=>$value1)
    {
        foreach($value1 as $key2=>$value2)
        {
            if($key2 == $value['epg_channel_id'])
            {
                $value[$key2]=$value2;
            }
        }
    }
    $new_array[$key]=$value;
}
print_r($new_array);

DEMO

1 Comment

Yes but last loop also iterate once per loop as it has only single element
1

You can key exists or not using array_key_exists in second array then add it to new array

Working Demo: https://eval.in/863359

$array = Array
(
    Array
    (
        'num' => 1,
        'name' => 'name 1',
        'epg_channel_id' => 'ch111',
        'added' => '1505435915',
    ),

    Array
    (
        'num' => 2,
        'name' => 'name 2',
        'epg_channel_id' => 'ch222',
        'added' => '1505435915',
    ),

    Array
    (
        'num' => 3,
        'name' => 'name 3',
        'epg_channel_id' => 'ch333',
        'added' => '1505435915',
    ),

    Array
    (
        'num' => 4,
        'name' => 'name 4',
        'epg_channel_id' => 'ch444',
        'added' => '1505435915'

    )
);
$array2 = Array
(
    Array
    (
        'ch000' => 'Um9jayBJbiBSaW8='
    ),

    Array
    (
        'ch111' => 'Um9jayBJbiBSaW8='
    ),

    Array
    (
        'ch222' => 'Um9jayBJbiBSaW8='
    ),

    Array
    (
        'ch333' => 'Um9jayBJbiBSaW8='
    ),

    Array
    (
        'ch444' => 'Um9jayBJbiBSaW8='
    )
);

$newArray =[];
foreach ($array as $key => $value) {
    foreach ($array2 as $key2 => $value2) {
        if (array_key_exists($value['epg_channel_id'], $value2)) {
            $value[$value['epg_channel_id']] = $value2[$value['epg_channel_id']];
        }
    }
    $newArray[] = $value;
}

echo "<pre>"; 
print_r($newArray);

Comments

0

array_merge_recursive works well for associated array that have keys are string. Numeric keys will be appended. From php.net

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

You have to convert your array to string keys, or using one loop to merge child arrays one by one.

Comments

0

Try this . I hope it will solve your problems. I have tested it.

foreach ($array1 as $key => $value){
       // echo $key;
        foreach ($array2 as $i =>$item){
            foreach ($item as $j=>$subitem){
                if($value['epg_channel_id'] == $j){
                    $array1[$key][$j] = $subitem;
            }
            }
        }
    }


print_r($array1);

Comments

0

try to read the value of 'epg_channel_id' from array1 and insert it to array1 itself from getting 'ch111' from array2

$ch_name = $array1[$i]['epg_channel_id'];
$id = $array1[$i]['num'];

$ch_value = $array2[$id]['$ch_name'];

$array1[$i]["$ch_name"] =  $ch_value;

try to put in foreach for every array

2 Comments

its multidimensional array, you can not access like this
try edited code. i hvn't noticed the multidimensional array
0
$new_arr = [];
foreach($arr1 as $val){
    foreach($arr2 as $val2){
        if(array_key_exists($val['epg_channel_id'], $val2)){
            $val[$val['epg_channel_id']] = $val2[$val['epg_channel_id']];
            break;
        }
    }
    $new_arr[] = $val;
}
print_r($new_arr);

Comments

0

The bad news is that your second array is not suitably structured to serve as a lookup array. The good news is that the step to flatten the structure into a simple associative array is quite easy.

Once the lookup is declared, just use a loop and modify-by-reference as you use array union syntax to append the desired key-value pairs.

I do not recommend any answers that are using nested loops -- they will not perform efficiently.

Code: (Demo)

$lookup = array_merge(...$array2);
foreach ($array as &$row) {
    $row += [$row['epg_channel_id'] => $lookup[$row['epg_channel_id']]];
}
var_export($array);

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.