Search code examples
phparrayssub-array

How to insert array elements as sub array like first element is the parent of second,second is the parent of third and so on?


I need to convert an array that is like $data = array('Image','Thumbnail','size') to $data= array('Image'=>array('Thumbnail'=>array('size'=>'test'))); format. How it will be possible?. I had tried something like below.

$count= count($data);
$last = $count-1;
for($i=$count-2;$i>=0;$i--)
{
  $newArray[$data[$i]][$data[$last]]='test'; 
  $last=$i;

}

but it gives output as

Array(
[thumbnail] => Array
    (
        [type] => test
    )

[image] => Array
    (
        [thumbnail] => test
    ))

Any help will be appreciated. Thank you :-)


Solution

  • Do you have other further considerations?

    The following code is simply to do so:

    <?php
    $data = array('Image','Thumbnail','size');
    $newArray[$data[0]][$data[1]][$data[2]]='test'; 
    var_dump($newArray);
    

    Or you could use for loop like this:

    <?php
    $data = array('Image','Thumbnail','size');
    $result=array();
    for($i=(count($data)-1);$i>=0;$i--){
        if($i==(count($data)-1))
            $result[$data[$i]]='test';
        else{
            $result[$data[$i]]=$result;
            unset($result[$data[$i+1]]);
        }
    }