拜托,我需要帮助.如何通过PHP转换我的数组
Array ( [0] => Apple [1] => Orange [2] => Tomato )
对此
Array ( [Apple] => Array ( [Orange] => Array ( [Tomato] => Array() ) ) )
我不知道我的数组中有多少元素.谢谢大家.
试试这个:
$array = array('apple','orange','tomato'); $count = count($array) - 1; $tempArray = array(); for($i = $count; $i >= 0; $i--) { $tempArray = array($array[$i] => $tempArray); }
试试看:
$target = array(); $value = array(); $path = array('apple', 'orange', 'tomato'); $rv = &$target; foreach($path as $pk) { $rv = &$rv[$pk]; } $rv = $value; unset($rv); print_r($target);
输出:
Array ( [apple] => Array ( [orange] => Array ( [tomato] => Array ( ) ) ) )
更新1:解释
这里我使用引用/变量别名来遍历动态的密钥堆栈.该引用使得可以使用堆栈而不是通常更精益的递归.此外,此代码可防止覆盖$target
数组中的现有元素.有关参考文献的更多详细信息,请参阅参考资料解释
$target = array(); //target array where we will store required out put $value = array(); //last value i.e. blank array $path = array('apple', 'orange', 'tomato'); //current array $rv = &$target; //assign address of $target to $rv (reference variable) foreach($path as $pk) { $rv = &$rv[$pk]; // Unused reference [ex. $rv['apple'] then $rv['apple']['orange'] .. so on ] - actually assigned to $target by reference print_r($target); echo '-----------------
'; } $rv = $value; //here $rv have unused refernce of value tomato so finally assigned a blank array to key tomoto // unset($rv); // Array copy is now unaffected by above reference echo "final array
"; print_r($target);
输出:
Array ( [apple] => ) ----------------- Array ( [apple] => Array ( [orange] => ) ) ----------------- Array ( [apple] => Array ( [orange] => Array ( [tomato] => ) ) ) ----------------- final array Array ( [apple] => Array ( [orange] => Array ( [tomato] => Array ( ) ) ) )
在交代的输出,你可以跟踪的价值$target
在foreach
循环
产量
Array ( [0] => Apple [1] => Orange [2] => Tomato [3] => Banana [4] => Papaya ) Array ( [Apple] => Array ( [Orange] => Array ( [Tomato] => Array ( [Banana] => Array ( [Papaya] => Array ( ) ) ) ) ) )
码
$fruits = [ "Apple", "Orange", "Tomato", "Banana", "Papaya" ]; // Result Array $result = [ $fruits[count($fruits) - 1] => [] ]; // Process for ($counter = count($fruits) - 2; $counter >= 0; $counter--) { $temp = $result; unset($result); $result[$fruits[$counter]] = $temp; } // Display echo "".print_r($fruits, true).""; echo "".print_r($result, true)."";