2

I'm struggling with the final step on a function that I am writing to clean up a multi-dimensional array. I want the function to loop through the array (and any sub-arrays) and then return a cleaned array.

Whilst I can use array_walk_recursive to output the cleaned data, I'm struggling with returning the data as an array in the same structure as the inputted. Can anyone help? Any help greatly appreciated....

Here's my code:

function process_data($input){
    function clean_up_data($item, $key)
    {
        echo strip_tags($item) . ' '; // This works and outputs all the cleaned data
        $key = strip_tags($item);     // How do I now output as a new array??
        return strip_tags($item);
    }
    array_walk_recursive($input, 'clean_up_data');
}

$array = process_data($array);  // This would be the ideal usage
print_r($array);  // Currently this outputs nothing
5
  • You want to return an array with all the "$key"s (not multidimensional) array? Commented Sep 9, 2013 at 10:20
  • 1
    Official document has a nice example for you to follow. Commented Sep 9, 2013 at 10:22
  • 1
    how about not wrapping a function definition in a callable function and just use &$item, &$key in your callback (check the examples in the manual). This is where references might just prove useful Commented Sep 9, 2013 at 10:23
  • @djot I would like to return the array with the same multidimensional structure as inputted. All the function would do is clean the data... Commented Sep 9, 2013 at 10:24
  • Thank you @Alireza Fallah Problem now solved! Commented Sep 9, 2013 at 10:35

2 Answers 2

2

you can use array_walk_recursive like that :

<?php
$arr = array(...);
function clean_all($item,$key)
{
$item = strip_tags($item);
}
array_walk_recursive($arr , 'clean_all');
?>

OR :

this is a recursive function , i think it solves your problem :

<?php
    function clean_all($arr)
    {
    foreach($arr as $key=>$value)
    {
       if(is_array($value)) $arr[$key] = clean_all($value);
       else  $arr[$key] = strip_tags($value);
    }
    return $arr;
    }

     ?>
Sign up to request clarification or add additional context in comments.

Comments

2

you need to pass the value by reference

function clean_up_data(&$item, $key)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.