donglan8999 2018-02-15 11:20
浏览 130
已采纳

需要合并数组,但如果重复则只留下一个值

I have two arrays with the same keys but different values. I need to merge it but if the values are the same leave only one of this

$array1 = array('firstname'=> $may_name, 'lastname'=>$my_last_name, 'address'=>$addres_1);

$array2 = array('firstname'=> $may_name, 'lastname'=>$my_last_name, 'address'=>$addres_2);

I need to get:

$array_result = array('firstname'=> $may_name, 'lastname'=>$my_last_name, 'address'=>$addres_1, 'address'=>$addres_2);

can anybody help to solve this? array_merge does not work for me..

  • 写回答

1条回答 默认 最新

  • duanlie4621 2018-02-15 11:24
    关注

    First you need to merge 2 arrays, using array_merge() function. then get the unique elements from the array using array_unique() function will get you the result

    var_dump(array_unique(array_merge($array1, $array2)));
    

    Edit

    If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. php doc

    Thanks @Marco

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数