Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP recursive multidimensional loop

$printArr = recursive($newArray); //calls recursive function
$data = [];
var_dump($data);
var_dump($printArr);
    function recursive($array, $level = 0)
    {
        $searchingValue = 'tableName';
        foreach($array as $key => $value)
        {
                //If $value is an array.
                if(is_array($value))
                {
                    recursive($value, $level + 1);
                } 
                else
                {
                    //It is not an array, so print it out.
                    if($key == $searchingValue)
                    {
                        echo "[".$key . "] => " . $value, '<br>';
                        $data[] = $value;
                    }
                }
        }
    }

So I have this function and I am trying to save $value value into $data[] array. But it always returns it empty and I don't know why I can't get $value saved outside the function. If i echo $value I get what i need but like I've mentioned the variables doesn't get saved in this case - table names.

like image 584
Tinabot Avatar asked Jul 20 '18 11:07

Tinabot


1 Answers

You need to pass the $data to your recursive function. Also you need to return the $data.

Try this code :

function recursive($array, $level = 0, $data =[])
{
    $searchingValue = 'tableName';
    foreach($array as $key => $value)
    {
            //If $value is an array.
            if(is_array($value))
            {
                recursive($value, $level + 1 , $data);
            } 
            else
            {
                //It is not an array, so print it out.
                if($key == $searchingValue)
                {
                    echo "[".$key . "] => " . $value, '<br>';
                    $data[] = $value;
                }
            }
    }
    return $data;
}
like image 200
Praveen S Avatar answered Nov 19 '22 14:11

Praveen S