How to use array_walk_recursive

前端 未结 3 1462
遥遥无期
遥遥无期 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: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!

提交回复
热议问题