How to use array_walk_recursive

前端 未结 3 1463
遥遥无期
遥遥无期 2021-01-13 15:20

How can I use array_walk_recursive() instead of this:

function check_value($val){
  if(is_array($val)){
    foreach($val as $key => $value)
          


        
相关标签:
3条回答
  • 2021-01-13 15:50

    I think this should do the same thing. Note that argument of a function is passed as a reference (i.e. &$value).

    array_walk_recursive($array, function(&$value) {
        $value = clean_value($value);
    });
    

    For older PHP versions:

    function check_value(&$value) {
        $value = clean_value($value);
    }
    array_walk_recursive($array, 'check_value');
    
    0 讨论(0)
  • 2021-01-13 15:52

    This should work:

    function check_value ( $val ) {
        if ( is_array ( $val ) ) array_walk_recursive ( $val, 'check_value' );
        return clean_value ( $val );
    }
    
    0 讨论(0)
  • 2021-01-13 15:55

    I would rewrite the clean_value function to take a reference argument. For example, these two snippets are functionally identical:

    1:

    function clean_value($value) {
        //manipulate $value
        return $value;
    }
    
    $value = clean_value($value);
    

    and

    2:

    function clean_value(&$value) {
        //manipulate $value
    }
    
    clean_value($value);    
    

    For the latter (2), we can use it in array_walk_recursive as follows:

    array_walk_recursive($value_tree, 'clean_value');
    

    If we can't edit clean_value, I would solve it as follows:

    $clean_by_reference = function(&$val) {
        $val = clean_value($val);
    };
    array_walk_recursive($value_tree, $clean_by_reference);
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题