combine 2 associative arrays where values match
I have 2 associative arrays: $arr1 & $arr2. I'd like to create $arr3, which would combine 'name' and 'character' if the dates match...if the dates don't match, then just the character:
Here's $arr1:
Array
(
[0] => stdClass Object
(
[date] => 2010/01/01
[name] => Mario Lopez
)
[1] => stdClass Object
(
[date] => 2010/01/02
[name] => Lark Voorhies
)
)
Here's $arr2:
Array
(
[0] => Array
(
[date] => 2010/01/01
[character] => AC Slater
)
[1] => Array
(
[date] => 2010/01/02
[character] => Lisa Turtle
)
[2] => Array
(
[date] => 2010/01/03
[character] => Kelly Kapowski
)
开发者_开发问答)
Using array_intersect gives the following error: "Object of class stdClass could not be converted to string".
Here's what I'd like to get, if it's possible (ie $arr3):
Array
(
[0] => stdClass Object
(
[date] => 2010/01/01
[name] => Mario Lopez
[character] => AC Slater
)
[1] => stdClass Object
(
[date] => 2010/01/02
[name] => Lark Voorhies
[character] => Lisa Turtle
)
[2] => stdClass Object
(
[date] => 2010/01/03
[character] => Kelly Kapowski
)
)
This function was posted on php.net and I've been using it for quite a while. It should do what you are asking for
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;
}
Usage:
$array = array_extend($orig_array,$new_array);
Note that you will either have to convert your objects to arrays or modify the function to convert the object to an array on the fly ($a = (array) $a);
Edit:
Original source http://www.php.net/manual/en/function.array-merge.php#95294
Note that I made a small modification to resolve an issue with the given function where it would not properly extend an array with numeric keys
精彩评论