I have 2 arrays. Is it possible to create output array and add keys/values from first to the second one? My arrays looks like:
The first:
Array
(
[0] => Array
(
[id] => 11
[expire] => undefined
)
[1] => Array
(
[id] => 12
[expire] => undefined
)
[2] => Array
(
[id] => 6
[expire] => 8
)
[3] => Array
(
[id] => 10
[expire] => 4
)
)
The second:
Array
(
[0] => Array
(
[id] => 6
[realname] => to_es.gif
[extension] => gif
[filesize] => 57885
)
[1] => Array
(
[id] => 10
[realname] => to_joomla_2_customer_view.gif
[extension] => gif
[filesize] => 77182
)
[2] => Array
(
[id] => 11
[realname] => to_nl.gif
[extension] => gif
[filesize] => 10990
)
[3] => Array
(
[id] => 12
[realname] => to_PL_1.gif
[extension] => gif
[filesize] => 52826
)
)
How I'm getting the output array:
Array
(
[0] => Array
(
[id] => 6
[realname] => to_es.gif
[extension] => gif
[filesize] => 57885
[expire] => 8
)
[1] => Array
(
[id] => 10
[realname] => to_joomla_2_customer_view.gif
[extension] => gif
[filesize] => 77182
[expire] => 4
)
[2] => Array
(
[id] => 11
[realname] => to_nl.gif
[extension] => gif
[filesize] => 10990
[expire] => undefined
)
[3] => Array
(
[id] => 12
[realname] => to_PL_1.gif
[extension] => gif
[filesize] => 52826
[expire] => undefined
)
)
Try this:
function my_array_merge($first,$second) {
$new = array();
foreach ($first as $f_item) {
foreach ($second as $i => $s_item) {
if ($f_item['id']===$s_item['id']) {
$new[] = $f_item + $s_item;
unset($second[$i]);
break;
}
}
}
usort($new, function($a,$b) {
return $a['id'] - $b['id'];
});
return $new;
}
Example on Ideone: http://ideone.com/TQIIkH
I'm supposing your first array as $array1
and second as $array2
you can loop within first array and then loop in second conmparing id
and when found mix both array in a new one
$new_array = array();
for($i=0; $i<count($array1); $i++)
{
foreach($array2 as $key => $data)
{
if($data['id'] == $array1[$i]['id'])
{
$new_array[] = array('id' => $array1[$i]['id'], 'realname' => $data['realname'], 'extension' => $data['extension'], 'filesize' => $data['filesize'], 'expire' => $array1[$i]['expire']);
}
}
}
var_dump($new_array);
this will output
array(4) {
[0]=>
array(5) {
["id"]=>
string(2) "11"
["realname"]=>
string(9) "to_nl.gif"
["extension"]=>
string(3) "gif"
["filesize"]=>
string(5) "10990"
["expire"]=>
string(9) "undefined"
}
[1]=>
array(5) {
["id"]=>
string(2) "12"
["realname"]=>
string(11) "to_PL_1.gif"
["extension"]=>
string(3) "gif"
["filesize"]=>
string(5) "52826"
["expire"]=>
string(9) "undefined"
}
// and so on