我有一个像下面这样的多维数组:
$data = array (
'department1' =>array(
'user1' => array(
'building1' => array(
'room1' => array(
'active' =>'false'
),
'room2' => array(
)
),
'building2' => array(
'room4' => array(
),
'room3' => array(
)
),
)
)
);
我想要做的是检查房间是否为空.如果为null,我应该设置一个值active =>测试.
我到目前为止所做的代码是:
foreach($data as $departments => $department){
foreach ($department as $users => $user){
foreach($user as $buildings => $building) {
foreach($building as $key => $value){
if ($data[$departments][$users][$buildings][$key] == null) {
$data[$departments][$users][$buildings][$key]['active'] = 'test';
}
}
}
}
}
它正在工作,但我想知道是否有一种最好的其他方式来实现它而不需要太多的foreach.
我的输出是:
Array
(
[department1] => Array
(
[user1] => Array
(
[building1] => Array
(
[room1] => Array
(
[active] => false
)
[room2] => Array
(
[active] => test
)
)
[building2] => Array
(
[room4] => Array
(
[active] => test
)
[room3] => Array
(
[active] => test
)
)
)
)
)
有帮助吗?谢谢.
最佳答案 使用以下递归函数,该函数接受并通过引用返回值(可以与任何项深度/层次结构一起使用):
function &checkRoom(&$data) {
foreach ($data as $k => &$v) {
if (strpos($k, "room") === 0 && empty($v)) $v = ["active" => "test"];
if (is_array($v)) checkRoom($v);
}
return $data;
}
$data = checkRoom($data);
print_r($data);
输出:
Array
(
[department1] => Array
(
[user1] => Array
(
[building1] => Array
(
[room1] => Array
(
[active] => false
)
[room2] => Array
(
[active] => test
)
)
[building2] => Array
(
[room4] => Array
(
[active] => test
)
[room3] => Array
(
[active] => test
)
)
)
)
)