0

我有以下两个arrays

$array1 = array
    (
        'Name' => 'Scott',
        'Department' =>  'Sales',
        'Location' => 'USA',
        'Details' => array
            (
                15 => '90%', 
                16 => '75%',
                17 => '50%',
                18 => '60%',
                19 => '50%',
                20 => '45%',  
            ),
          );
$array2 = array
(
    'Action' => 'Imp',
    'Name' => 'Scott',
    'Department' => 'Sales',
    'Location' => 'Canada', 
    'Details' => array 
    (
             15 => '20%', 
             16 => '15%',
             17 => '25%',
             18 => '10%',
    ),
);

结果应该是:

$result_arr = array
        (
            'Action' => 'Imp',
            'Name' => 'Scott',
            'Department' =>  'Sales',
            'Location' => 'Canada',
            'Details' => array
                (
                    15 => '20%', 
                    16 => '15%',
                    17 => '25%',
                    18 => '10%',
                    19 => '50%',
                    20 => '45%',  
                ),
              );

我试过了array_mergearray union (+) operator但没有一个适合我的要求。

4

5 回答 5

1

尝试这个

$final= array_merge($array1,$array2);
$final['Details']= $final['Details']+$array1['Details'];
asort($final);
echo "<pre>"; print_r($final);

输出 :

Array
(
    [Location] => Canada
    [Action] => Imp
    [Department] => Sales
    [Name] => Scott
    [Details] => Array
        (
            [15] => 20%
            [16] => 15%
            [17] => 25%
            [18] => 10%
            [19] => 50%
            [20] => 45%
        )

)
于 2013-05-30T14:53:36.183 回答
1
array_replace_recursive($array1, $array2);
于 2013-05-30T15:01:54.803 回答
1

看起来结果数组应该看起来像$array2并且$array2['Details']应该使用来自的键进行扩展$array1['Details']

$result_arr = $array2;
$result_arr['Details'] += $array1['Details'];
于 2013-05-30T14:48:53.743 回答
0

提供的信息很少,我可以使用以下方法获得您的结果:

$array = array_merge($array1, $array2);
$array['Details'] = $array2['Details'] + $array1['Details'];
print_r($array);

结果:

Array
(
    [Name] => Scott
    [Department] => Sales
    [Location] => Canada
    [Details] => Array
        (
            [15] => 20%
            [16] => 15%
            [17] => 25%
            [18] => 10%
            [19] => 50%
            [20] => 45%
        )

    [Action] => Imp
)
于 2013-05-30T14:42:57.663 回答
0
$array2['Details'] = array_merge($array1['Details'], $array2['Details']);
$result = $array2;
于 2013-05-30T14:55:59.130 回答