-1

我有 2 个数组

$data1 = array(
    ['Ngay'=>'15-10-2013','esoluz'=>'5'],
    ['Ngay'=>'16-10-2013','esoluz'=>'3'],
    ['Ngay'=>'17-10-2013','esoluz'=>'7']
);

$data2 = array(
    ['Ngay'=>'15-10-2013','google'=>'10'],
    ['Ngay'=>'16-10-2013','google'=>'8']
);

我希望它变成:

$result = array(
    ['Ngay'=>'15-10-2013','esoluz'=>'5','google'=>'10'],
    ['Ngay'=>'16-10-2013','esoluz'=>'3','google'=>'8'],
    ['Ngay'=>'17-10-2013','esoluz'=>'7'],
)

因为我需要一个像 $result 这样的数组来对其进行 json_encode 来制作图表,但这让我感到困惑。所以,感谢任何有用的想法!

4

3 回答 3

3

http://sandbox.onlinephpfunctions.com/code/d2ce9d28f355660ec621d952c448614997f0b4a6

$data1 = array(
    ['Ngay'=>'15-10-2013','esoluz'=>'5'],
    ['Ngay'=>'16-10-2013','esoluz'=>'3'],
    ['Ngay'=>'17-10-2013','esoluz'=>'7']
);

$data2 = array(
    ['Ngay'=>'15-10-2013','google'=>'10'],
    ['Ngay'=>'16-10-2013','google'=>'8']
);
// Yet a working function
function yawf($arr1, $arr2) {
    $result = array();
    $temp = array();
    foreach($arr1 as $k => $v) {
        $temp[$v['Ngay']] = $v;
    };

    foreach($arr2 as $k => $v) {
        if(isset($temp[$v['Ngay']])) {
            $temp[$v['Ngay']]['google'] = $v['google'];
        }
        else {
            $temp[$v['Ngay']] = $v;
        }
    };

    foreach($temp as $k => $v) {
        $result[] = $v;
    }

    return $result;
}

print_r(yawf($data1, $data2));

echo json_encode(yawf($data1, $data2));
于 2013-10-17T09:29:16.930 回答
1

使用方法array_merge()之后使用array_unique()生成唯一值,然后打印 JSON 结果。你的代码会像 -

$result_arr = array_merge($data2, $data1);
$result_arr = array_unique($result_arr);

$result_arr = array();
foreach($data1 as $value){
    $result_arr[$value['Ngay']] = $value;
}
foreach($data2 as $value){
    if(array_key_exists($value['Ngay'],$result_arr)){
        $result_arr[$value['Ngay']] = array_merge($result_arr[$value['Ngay']],$value);
    }else{
         $result_arr[$value['Ngay']] = $value;
    }
}
$result = json_encode($result_arr);
于 2013-10-17T09:19:08.483 回答
0
$outArray = array();
foreach($data1 as $item){
    $outArray[$item['Ngay']] = $item;
}
foreach($data2 as $item){
    if(array_key_exists($item['Ngay'],$outArray)){
        $outArray[$item['Ngay']] = array_merge($outArray[$item['Ngay']],$item);
    }else{
         $outArray[$item['Ngay']] = $item;
    }
}

PHP小提琴: http: //phpfiddle.org/main/code/v8f-miu

于 2013-10-17T09:18:03.217 回答