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 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?