我有一个像单向列表的数组:
array( 'data1' => <some data>,'next' => array( 'data2' => <some data>,'next' => array( 'data3' => <some data>,'next' => array( 'data4' => <some data>,'next' => array( 'data5' => <some data>,'next' => ..... etc to data n ); ); ); ); );
你不是在寻找阵列的反面,但是你正在寻找相反的东西.
原文链接:https://www.f2er.com/php/138683.html首先要更好地理解这种逆转可能会对你有所帮助.
您需要每个元素的父元素.如果您遍历下一个,则父级始终是前一个.因此,如果您将前一个元素添加为父元素,那么数组的最后一个元素就是您要查找的元素.
所以听起来很直接.更难的部分是用所谓的变量别名/引用来表达它.
让我们添加所有父项,并在遍历数组时,在引用它之后删除“下一个”条目:
/* traverse the path on 'next' and keep prevIoUs to set 'parent' of current */ $walk = &$array; // start at root node while ($walk) { if (isset($prevIoUs)) { $walk['parent'] = &$prevIoUs; } $prevIoUs = &$walk; $hasNext = array_key_exists('next',$walk); if ($hasNext) { $walk = &$walk['next']; unset($prevIoUs['next']); } else { break; } } unset($prevIoUs);
写入最后一个元素然后将包含您正在寻找的数组.最后一个元素是$步行:
print_r($walk);
哪个给你(Demo):
Array ( [data5] => <some data5> [parent] => Array ( [data4] => <some data4> [parent] => Array ( [data3] => <some data3> [parent] => Array ( [data2] => <some data2> [parent] => Array ( [data1] => <some data1> ) ... )
希望这是有帮助的,可以理解的.