简体   繁体   中英

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 :-)

You can create your own method to create such a structure by just traversing the array and creating an inner child for each element.

function createPath($array) {
    $result = [];
    $current = &$result;
    foreach ($array as $node) {
        $current[$node] = [];
        $current = &$current[$node];
    }
    return $result;
}

This can also be done with array_reduce and an reversed array: ( array_reduce doumentation , array_reverse documentation )

$result = array_reduce(array_reverse($array), function($carry, $element) {
       return [$element => $carry]; 
    }, []);

While the foreach solution will build the structure from the outer element to the most inner element, the array_reduce solution will build it from the inner to the outer elements.

Both solutions will create the output:

[
    'Image' => [
        'Thumbnail' => [
            'size' => []
        ]
    ]
]

If you want the most inner key to contain another value than an empty array, you can change the intial value of the array_reduce carry to that desired value or add another parameter to the createPath function, that adds this value as the most inner key.

You can use this, with very basic logic:

$array = array('Image','Thumbnail','size', 'test');
$a = [];
$i = count($array)- 1;
$a[$array[$i-1]] = $array[$i];
--$i;
while($i >= 1 ) {
    $a[$array[$i-1]] = $a;
    unset($a[$array[$i]]);
    --$i;
}

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]]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM