duanmao1319 2016-07-09 15:16
浏览 40
已采纳

PHP比较键并从多维数组中更改某些值,并使用简单数组中的相应键值

I have two arrays (one simple and one multidimensional) and I want to verify if certain keys from the multidimensional array have empty values and replace them with their correspondent values from the simple array.

Solution for both simple arrays and/or 2D arrays is here:

PHP Compare and change certain elements in multidimensional arrays

But what would be the solution in the situation above?

Example of simple array:

$superheroes_complete = array(
    1 => 'one',
    'two' => 'two',
    3 => 'three',
    'email' => 'peterparker@mail.com',
    5 => 'cinco',
    6 => 'six',
    'name' => 'Clark Kent',
    8 => 'eight'
);

Example of multidimensional array:

$superheroes_empty = array(
    "spiderman" => array(
        "name" => "Peter Parker",
        "email" => "",
    ),
    "superman" => array(
        "name" => "",
        "email" => "clarkkent@mail.com",
    ),
    "ironman" => array(
    "name" => "Harry Potter",
    "email" => "harrypotter@mail.com",
    )
);

Expectation:

$superheroes_empty = array(
    "spiderman" => array(
        "name" => "Peter Parker",
        "email" => "peterparker@mail.com",
    ),
    "superman" => array(
        "name" => "Clark Kent",
        "email" => "clarkkent@mail.com",
    ),
    "ironman" => array(
        "name" => "Harry Potter",
        "email" => "harrypotter@mail.com",
    )
);

Thank you in advance.

  • 写回答

2条回答 默认 最新

  • douji1077 2016-07-09 15:26
    关注

    Here is one way to do this using array_walk_recursive:

    array_walk_recursive($superheroes_empty, function(&$v, $k) use ($superheroes_complete) {
        if ($v === '' && isset($superheroes_complete[$k])) {
            $v = $superheroes_complete[$k];
        }
    });
    

    This will fill in any empty values if a corresponding key is found in $superheroes_complete. Since this makes replacements by reference, it will directly change the $superheroes_empty array, so if you still need the one with empty values, make a copy before using this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?