我有一个数组
$rules = array(
'name' => array(
'isRequired' => array(
'message' => 'Name Required'
),
'isBetween' => array(
'value' => array(5,15),
'message' => 'Between 5 to 15 characters'
),
'isAlphaLower' => array(
'message' => 'Should be Alpha lower'
),
'isLength' => array(
'value' => 20,
'message' => 'Length should be 20 chracters'
)
),
'email' => array(
'isEmail' => array(
'message' => 'Email should be valid'
),
'isRequired' => array(
'message' => 'Email Required'
),
),
'pPhone' => array(
'isNumber' => array(
'message' => 'Only Numbers'
)
)
);
我需要删除键名为message
的所有数组元素。我该怎么做?
答案 0 :(得分:2)
嵌套的foreach,参考。
foreach( $rules as $field => &$fieldrules ) { foreach( $fieldrules as $rulename => &$rulesettings ) { unset( $rulesettings['message'] ); } }
答案 1 :(得分:1)
如果您要删除密钥为'message'
三个级别的所有键/值对,您可以尝试以下操作:
foreach ($rules as $k1 => $arr) {
foreach ($arr as $k2 => $arr2) {
foreach ($arr2 as $k3 => $arr3) {
if ($k3 == 'message') {
unset($rules[$k1][$k2][$k3]);
}
}
}
}
答案 2 :(得分:1)
在嵌套unset()
中使用foreach
loop:
foreach($rules as &$fieldrules)
foreach($fieldrules as &$ruleparams)
if(isset($ruleparams['message'])) // E_STRICT
unset($ruleparams['message']);
注意变量前的&
。这是一个参考传递。这样做很重要,这样我们就可以修改实际的数组,而不是副本。