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

时间:2016-07-09 15:16:12

标签: php arrays multidimensional-array

我有两个数组(一个简单和一个多维),我想验证来自多维数组的某些键是否具有空值,并用简单数组中的对应值替换它们。

简单数组和/或2D数组的解决方案如下:

PHP Compare and change certain elements in multidimensional arrays

但上述情况会有什么解决方案?

简单数组的示例:

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

多维数组示例:

$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",
    )
);

期望:

$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",
    )
);

提前谢谢。

2 个答案:

答案 0 :(得分:1)

以下是使用array_walk_recursive执行此操作的一种方法:

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

如果在$superheroes_complete中找到相应的密钥,则会填写任何空值。由于这会通过引用进行替换,因此它将直接更改$superheroes_empty数组,因此如果您仍需要具有空值的数组,请在使用之前进行复制。

答案 1 :(得分:0)

您也可以使用此

foreach($superheroes_empty as $key =>$array){
    foreach($array as $key1=>$data){        
        if(empty($data)){           
            $superheroes_empty[$key][$key1] = $superheroes_complete[$key1];         
            }
        }   
    }
    echo "<pre>";print_r($superheroes_empty);