You have not make your output clearly, suppose you expected output is like this:
array(2) {
[123456]=>
array(4) {
["firstname"]=>
string(6) "George"
["lastname"]=>
string(6) "George"
["personal_id"]=>
int(123456)
[0]=>
string(5) "test1"
}
[654321]=>
array(4) {
["firstname"]=>
string(4) "John"
["lastname"]=>
string(4) "John"
["personal_id"]=>
int(654321)
[0]=>
string(5) "test2"
}
}
here is the code, and the demo, hope it helps.
<?php
$val = array (
'1' => array(
'0' => 'test1',
'1' => '123456',
),
'2' => array(
'0' => 'test2',
'1' => '654321',
)
);
$results = array (
'5' => array
(
'login' => '123456',
'firstname' => 'George',
'lastname' => 'George',
),
'8' => array(
'personal_id' => '654321',
'firstname' => 'John',
'lastname' => 'John',
)
);
/*
$indexOfPrimarykey is the nth of index as the specify id, to make it more universely, I used index.
You array is just the first and the last index, here also can use
reset($array); $first_key = key($array); to get the first key,
and
end($array); $last_key = key($array); to get the last key.
*/
function mergeArray($array, $indexOfPrimarykey)
{
$o = [];
array_walk($array, function($v) use($indexOfPrimarykey, &$o)
{
$keys = array_keys($v);
$k = $keys[$indexOfPrimarykey];
$value = $v[$k];
unset($v[$k]);
$o[$value] = $v;
});
return $o;
}
$val = mergeArray($val,1);
$results = mergeArray($results,0);
array_walk($val, function($v, $k) use(&$results)
{
$results[$k] += ['personal_id' => $k] + $v;
});
var_dump($results);