Alvaro Louzada
Alvaro Louzada

Reputation: 433

Merge second array into first array where row value in first array matches row key in second array

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.

Upvotes: 4

Views: 1118

Answers (8)

mickmackusa
mickmackusa

Reputation: 47874

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);

Upvotes: 0

simple guy
simple guy

Reputation: 673

$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);

Upvotes: 0

kojow7
kojow7

Reputation: 11384

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.

Upvotes: 2

Anu
Anu

Reputation: 558

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

Upvotes: 0

Nazmul Hasan
Nazmul Hasan

Reputation: 1977

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);

Upvotes: 0

Jigar Shah
Jigar Shah

Reputation: 6223

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);

Upvotes: 1

B. Desai
B. Desai

Reputation: 16436

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

Upvotes: 1

Tuan Duong
Tuan Duong

Reputation: 515

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.

Upvotes: 0

Related Questions