php - 如果值匹配,则将值附加到数组中的数组
问题描述:
Is there a way, with the two followings arrays to get another array which is the combination of those two arrays?
Array 1:
Array
(
[0] => Array
(
[a_id] => 9
[name] => Mario Lopez
)
[1] => Array
(
[a_id] => 8
[name] => Lisa Turtle
)
)
Array 2:
Array
(
[0] => Array
(
[b_id] => 1
[name] => AC Slater
)
[1] => Array
(
[b_id] => 2
[name] => Lisa Turtle
)
[2] => Array
(
[b_id] => 3
[name] => Kelly Kapowski
)
)
What I would like to get :
Array
(
[0] => Array
(
[b_id] => 1
[name] => AC Slater
)
[1] => Array
(
[a_id] => 8
[b_id] => 2
[name] => Lisa Turtle
)
[2] => Array
(
[b_id] => 3
[name] => Kelly Kapowski
)
[3] => Array
(
[a_id] => 9
[name] => Mario Lopez
)
)
The third array merges the two first arrays where the key name matches I have not found a builtin function and tried this solution without success: combine 2 associative arrays where values match.
Thank you,
Edit: sorry, I forgot to add Mario Lopez. My attempt was:
function array_extend($a, $b) {
foreach($b as $k=>$v) {
if( is_array($v) ) {
if( !isset($a[$k]) OR isset($v[0])) {
$a[$k] = $v;
} else {
$a[$k] = array_extend($a[$k], $v);
}
} else {
$a[$k] = $v;
}
}
return $a;
}
答
This probably is what you are looking for, although as @OldPadawan already pointed out in the comments to the question the actual result differs from the proposed one...
<?php
$a = [
[
'a_id' => 9,
'name' => 'Mario Lopez'
],
[
'a_id' => 8,
'name' => 'Lisa Turtle'
]
];
$b = [
[
'b_id' => 1,
'name' => 'AC Slater'
],
[
'b_id' => 2,
'name' => 'Lisa Turtle'
],
[
'b_id' => 3,
'name' => 'Kelly Kapowski'
]
];
$c = $a;
array_walk($b, function($be) use (&$c) {
$done = false;
array_walk($c, function(&$ce) use($be, &$done) {
if ($ce['name'] == $be['name']) {
$ce['b_id'] = $be['b_id'];
$done = true;
}
});
if ( ! $done) {
array_push($c, $be);
}
});
print_r($c);
The output of above code is:
Array
(
[0] => Array
(
[a_id] => 9
[name] => Mario Lopez
)
[1] => Array
(
[a_id] => 8
[name] => Lisa Turtle
[b_id] => 2
)
[2] => Array
(
[b_id] => 1
[name] => AC Slater
)
[3] => Array
(
[b_id] => 3
[name] => Kelly Kapowski
)
)