duanhongxian6982 2012-11-11 13:58
浏览 20
已采纳

用于使用具有相同键的不同数组值替换内部数组值的PHP数组方法

I'm trying to understand PHP array methods, so Id prefer using the array methods to solve this.

Here is my data:

$dataA =>
    array
      0 => 
        array
          'type' => string 'name' (length=4)
          'key' => string 'keywords' (length=8)
          'content' => string 'keywordA' (length=14)

$dataB =>
    array
      1 => 
        array
          'type' => string 'name' (length=4)
          'key' => string 'keywords' (length=8)
          'content' => string 'keywordB' (length=14)

What I'd like to do is have the two arrays merged and the final content key be:

$finalData =>
    array
      0 => 
        array
          'type' => string 'name' (length=4)
          'key' => string 'keywords' (length=8)
          'content' => string 'keywordB' (length=14)
                               ^-- notice here that the content has changed based on the fact that 'key' for both is 'keywords'

As you can see, the final content value is from $dataB.

  • 写回答

2条回答 默认 最新

  • dongqiang4986 2012-11-11 14:12
    关注

    Recursive replace does what you want

    $finalData = array_replace_recursive($dataA, $dataB);
    

    For this particular example, also plus operator will do what you want:

    $finalData = $dataB + $dataA;
    

    But you will have to specify arguments in different order.

    There is no such built-in function. You need something to replace only one specific key, only when other is equal it's equivalent in second array, moreover there are associative arrays in zero-indexed ones and you need to compare items only in second-level. If you look at it after describing, you may notice that it is not general functionality that everybody needs, so it is not included in standard function set.

    Assuming that key value is unique per array, here is solution without visible loops:

    $getKey = function($item){ return $item['key']; };
    $keysA = array_map($getKey, $dataA);
    $keysB = array_map($getKey, $dataB);
    $finalData = array_values(array_replace_recursive(
        array_combine($keysA, $dataA), 
        array_combine($keysB, $dataB) 
    ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程