merge array & rename key with php -
i have following 2 arrays of objects:
first array: $array1
array ( [0] => array ( [match] => 1 [when] => 2013-10-13 15:00:00 [a] => ad [b] => nip [winner] => c [closed] => 1 [event] => fragbite masters [format] => 3 ) [1] => array ( [match] => 2 [when] => 2013-10-13 15:00:00 [a] => vg [b] => ad [winner] => [closed] => 1 [event] => starseries [format] => 5 ) [2] => array ( [match] => 3 [when] => 2013-10-13 21:15:00 [a] => serbia [b] => portugal [winner] => [closed] => 1 [event] => esec [format] => 1 ) )
second array: $array2
array ( [0] => array ( [match] => 1 [a] => 58 [b] => 107 ) [1] => array ( [match] => 2 [a] => 174 [b] => 162 ) [2] => array ( [match] => 3 [a] => 64 [b] => 59 ) )
i this:
array ( [0] => array ( [match] => 1 [when] => 2013-10-13 15:00:00 [a] => ad [b] => nip [winner] => c [closed] => 1 [event] => fragbite masters [format] => 3 [per_a] => 58 [per_b] => 107 ) [1] => array ( [match] => 2 [when] => 2013-10-13 15:00:00 [a] => vg [b] => ad [winner] => [closed] => 1 [event] => starseries [format] => 5 [per_a] => 174 [per_b] => 162 ) [2] => array ( [match] => 3 [when] => 2013-10-13 21:15:00 [a] => serbia [b] => portugal [winner] => [closed] => 1 [event] => esec [format] => 1 [per_a] => 64 [per_b] => 59 ) )
where key name [a]
, [b]
second array have been modified [per_a]
, [per_b]
.
things tried merge both files:
array_merge & array_merge_recursive: both me result merged values of$array2
appended end of$array1
.
array_combine: wont work because$array1
,$array2
haven't equal number of elements.
this part of each file, both not equal in term of elements. if have answer me apreciated ! thx in advance !
try need modify keys in function. see demo
$match
: check key exists in both arrays.$wherekey1
$wherekey2
: pick values second array , put in new key$newkey1
,$newkey2
function key_compare_func($arr1, $arr2) { $newarray = array(); $match = "match"; $wherekey1 = "a"; $wherekey2 = "b"; $newkey1 = "per_a"; $newkey2 = "per_b"; if(is_array($arr1) && is_array($arr2)){ if($arr1[$match] == $arr2[$match] ){ $newarray = array_merge($arr1, array($newkey1 => $arr2[$wherekey1], $newkey2 => $arr2[$wherekey2])); } } return $newarray; } $modifiedarray = array_map("key_compare_func",$a1, $a2); echo '<pre>';print_r($modifiedarray);echo '</pre>';
output:
[0] => array ( [match] => 1 [when] => 2013-10-13 15:00:00 [a] => ad [b] => nip [winner] => c [closed] => 1 [event] => fragbite masters [format] => 3 [per_a] => 58 [per_b] => 107 ) [1] => array ( [match] => 2 [when] => 2013-10-13 15:00:00 [a] => vg [b] => ad [winner] => [closed] => 1 [event] => starseries [format] => 5 [per_a] => 174 [per_b] => 162 )
Comments
Post a Comment