开发者

How do i remove multiple array elements in PHP?

开发者 https://www.devze.com 2023-04-08 17:24 出处:网络
I have an array $rules = array( \'name\' => array( \'isRequired\' => array( \'message\' => \'Name Required\'

I have an array

$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'
        )
    )
);

I need to remove all array element with key name message. how do i do that?

thank you..


Nested foreach, by reference.

foreach( $rules as $field => &$fieldrules ) {
    foreach( $fieldrules as $rulename => &$rulesettings ) {
        unset( $rulesettings['message'] );
    }
}


Use unset() within a nested foreach loop:

foreach($rules as &$fieldrules)
  foreach($fieldrules as &$ruleparams)
    if(isset($ruleparams['message'])) // E_STRICT
      unset($ruleparams['message']);

Note the & before the variables. This is a pass by reference. It's important to do so here so that we modify the actual array and not a copy.


If you are tring to remove all key/value pairs where the key is 'message' three levels deep, you could try the following:

foreach ($rules as $k1 => $arr) {
    foreach ($arr as $k2 => $arr2) {
        foreach ($arr2 as $k3 => $arr3) {
            if ($k3 == 'message') {
                unset($rules[$k1][$k2][$k3]);
            }
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消