Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array in PHP [nesting]

Tags:

arrays

php

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.

like image 890
Nail Avatar asked Nov 30 '22 23:11

Nail


2 Answers

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>";
like image 197
Ahsan Avatar answered Dec 06 '22 06:12

Ahsan


Try This:

$array = array('apple','orange','tomato');
$count = count($array) - 1;
$tempArray = array();
for($i = $count; $i >= 0; $i--)
{
    $tempArray = array($array[$i] => $tempArray);
}
like image 27
devpro Avatar answered Dec 06 '22 07:12

devpro