please, I need help. How to convert my array via PHP
Array
(
[0] => Apple
[1] => Orange
[2] => Tomato
)
To this
Array
(
[Apple] => Array
(
[Orange] => Array
(
[Tomato] => Array()
)
)
)
And i do not know how many elements in my array. Thank all.
Output
Array
(
[0] => Apple
[1] => Orange
[2] => Tomato
[3] => Banana
[4] => Papaya
)
Array
(
[Apple] => Array
(
[Orange] => Array
(
[Tomato] => Array
(
[Banana] => Array
(
[Papaya] => Array
(
)
)
)
)
)
)
Code
$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>";
Try This:
$array = array('apple','orange','tomato');
$count = count($array) - 1;
$tempArray = array();
for($i = $count; $i >= 0; $i--)
{
$tempArray = array($array[$i] => $tempArray);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With