gosulove gosulove - 3 years ago 102
PHP Question

PHP compare two Array Keys and combine into a new Array(Wrong format)

I have two arrays and want to compare the same keys of array_1 and array_2 and combine them into a new Array like array_3

Coding

$array_1['value1']="";
$array_1['value2']="";
$array_1['value3']="";
$array_1['value4']="";
$array_1['value5']="";

$array_2['value1']="5";
$array_2['value3']="10";
$array_2['value5']="15";

/*
I want the format to be like this after merging.

$array_3['value1']="5";
$array_3['value2']="";
$array_3['value3']="10";
$array_3['value4']="";
$array_3['value5']="15";

*/

$results=array_merge_recursive($array_1,$array_2);
echo '<pre>',print_r($results),'</pre>';


enter image description here
By using array_merge_recursive, the array format is not what I want. Anyone has idea how to get the result format like the right side of the screenshot?

Answer Source

Ordinary array_merge should do the trick:

<?php

$array_1['value1']="";
$array_1['value2']="";
$array_1['value3']="";
$array_1['value4']="";
$array_1['value5']="";

$array_2['value1']="5";
$array_2['value3']="10";
$array_2['value5']="15";

/*
I want the format to be like this after merging.

$array_3['value1']="5";
$array_3['value2']="";
$array_3['value3']="10";
$array_3['value4']="";
$array_3['value5']="15";

*/

$results=array_merge($array_1,$array_2);
echo print_r($results);

The result:

Array
(
    [value1] => 5
    [value2] => 
    [value3] => 10
    [value4] => 
    [value5] => 15
)
1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download