Provides powerful array functionality in PHP, and provides two methods for merging arrays: Array_merge and Array_merge_ Recursive but for our ever-changing business, these built-in approaches don't exactly meet our requirements. As I am now encountering the problem of array merging, the requirement is this: there are two two-dimensional arrays, most of which have the same health name, but some health names may not exist in another array, What I need to do now is to copy all the health values from the second array into the first array (if the value of one of the two arrays is the same) it is obvious that the two methods built in are not sufficient (two methods simply copy the health values from the second array to the first corresponding kin)
$ar1 = array("color" => array("favorite" => "red","name"=>"test"));
$ar2 = array("color" => array("favorite" => "green","code"=>"code"));
print_r (array_merge ($ar1, $ar2));
print_r(array_merge_recursive ($ar1, $ar2));
You can see that array_merge just copies the value of each second array to the first array, and obviously the array is favorite.name by the array two code and Array_merge_ Recursive does not overwrite the same health name but once the two array health name is the same, it creates a new array and adds two of the values in the array to the new array
Here's how I customized the implementation:
/**
* @Author: -HTL
* @Email: [email protected]
* @DateTime: 2016-04-21 12:01:51
* @Description: 根据指定的健名将$ar2中的所有健值复制到$ar1对应的健值中
* @Return:$ar1
*/
function array_more_merge($ar1,$ar2,$key_name){
if(
!$ar1
|| !is_array($ar1)
|| count($ar1)<=0
|| !$ar2
|| !is_array($ar2)
|| count($ar2)<=0
|| !$key_name
|| strlen($key_name)<=0)
{
return $ar1;
}
- The For loop cannot be used because if the index in the array is not contiguous, using for may not complete the loop correctly
- such as $a =
- Array (
- 1 = = Array ("id" = 1), 8 = = Array ("id" = 2), 4 = = Array ("id" = 4));
- The number of arrays is 3, so only [1] is found, and [8][4] is not processed in the loop because $i <=count ($a) is not established
- for ($i =0; $i <=count ($a); $i + +) {print_r ($a [$i]); }
foreach ($ar1 as $i=>$items) {
foreach ($ar2 as $key=>$item) {
if($ar2[$key][$key_name]==$ar1[$i][$key_name]){
$keys = array_keys($ar2[$key]);
foreach ($keys as $name) {
$ar1[$i][$name] = $ar2[$key][$name];
}
}
}
}
return $ar1;
}
$ar1 = ‘{"1":{"cost":"1","id":"1","total_price":"5"},"2":{"cost":"2","id":"2","total_price":"10"},"4":{"cost":"4","id":"4","total_price":"20"}}‘;
$ar1 = json_decode($ar1,true);
$ar2 = ‘{"1":{"cost":"1","id":"1","total_price":"5"},"2":{"cost":"20","id":"2","total_price":"100"},"4":{"cost":"40","id":"4","total_price":"200"}}‘;
$ar2 = json_decode($ar2,true);
echo "array_merge_recursive:";
print_r(array_merge_recursive($ar1,$ar2));
echo "array_merge:";
print_r(array_merge($ar1,$ar2));
echo "array_more_merge:";
print_r($this->array_more_merge($ar1,$ar2,"id"));
die();
From for notes (Wiz)
PHP custom method implements array merging