在php中使用common字段组合两个数组

时间:2015-05-11 10:36:29

标签: php arrays

我需要使用关键字段组合两个数组。

$array1 = array( val1 => 'abc', val2 => '5' );
$array1 = array( val1 => 'bcd', val2 => '2' );

$array2 = array( val1 => 'abc', val3 => '1' );
$array2 = array( val1 => 'zzz', val3 => '3' );


array1:
val1    val2
abc       5 
bcd       2   

array2:
val1    val3
abc       1
zzz       3

结果必须如下;(要求)

val1          val2             val3
abc             5                1
bcd             2                0
zzz             0                3

现在,我开发了进一步需要一些修改来实现上表。

foreach($array1 as $ar1){
    $val1='';
    $val2='';
    $val3='';
    foreach($array2 as $ar2){
        if($ar1['val1']==$ar2['val1']){
           $val1=$ar1['val1'];
           $val2=$ar1['val2'];
           $val3=$ar2['val3'];
        }
    }

    $result=array(
        val1 => $val1,
        val2 => $val2,
        val3 => $val3
    );

}

这只捕获常见数据。

1 个答案:

答案 0 :(得分:2)

$result = array();

// Make $result an associative array, containing contents of $array1
foreach ($array1 as $e) {
    $e['val3'] = 0; // val3 defaults to 0
    $result[$e['val1']] = $e;
}

// Now merge in $array2
foreach ($array2 as $e) {
    if (isset($result[$e['val1']])) {
        $result[$e['val1']]['val3'] = $e['val3'];
    } else {
        $e['val2'] = 0; // val2 defaults to 0
        $result[$e['val1']] = $e;
    }
}

// Convert to indexed array
$result = array_values($result);

BTW,创建输入数组的正确方法是:

$array1 = array(array( 'val1' => 'abc', 'val2' => '5' ),
                array( 'val1' => 'bcd', 'val2' => '2' )
);

$array2 = array(array( 'val1' => 'abc', 'val3' => '1' ),
                array( 'val1' => 'zzz', 'val3' => '3' )
);