拜托,我需要帮助。如何通过PHP转换我的数组
Array
(
[0] => Apple
[1] => Orange
[2] => Tomato
)到这个
Array
(
[Apple] => Array
(
[Orange] => Array
(
[Tomato] => Array()
)
)
)我不知道我的数组里有多少元素。谢谢大家。
发布于 2015-12-22 07:18:42
输出
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 "<pre>".print_r($fruits, true)."</pre>";
echo "<pre>".print_r($result, true)."</pre>";发布于 2015-12-22 07:01:35
试试这个:
$array = array('apple','orange','tomato');
$count = count($array) - 1;
$tempArray = array();
for($i = $count; $i >= 0; $i--)
{
$tempArray = array($array[$i] => $tempArray);
}发布于 2015-12-22 07:17:26
试一试:
$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 '-----------------<br />';
}
$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<br />";
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循环中的值。
https://stackoverflow.com/questions/34410106
复制相似问题