Nee*_*eko 5 php arrays recursion loops multidimensional-array
$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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我有这个功能,我试图将$ value值保存到$ data []数组中.但它总是将它返回为空,我不知道为什么我不能在函数外部保存$ value.如果我回显$ value我得到了我需要的东西,但就像我提到的那样,变量在这种情况下不会被保存 - 表名.
您需要将$ data传递给递归函数。另外,您需要返回$ data。
试试这个代码:
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;
}
Run Code Online (Sandbox Code Playgroud)