John Davidson

php - Creating a nested array dynamically with for loop

0 comments
Message:


I have a loop that looks like this


$folder = [];

$explode = explode("/", $product->folder);

for($i = 0; $i < count($explode); $++)
{
$folder[$i] = 'test'
}

dd($folder);

what I'm trying to do here is to create a nested array depending on how many folders there are based on what I get from $explode.


So ideally what I want is this


[
"folder1" => [
"folder2" => "test"
]
]

and it would carry on being nested, so if my $product->folder looks like this cat1/cat2/cat3 then the array would looks like this


[
"cat1" => [
"cat2" => [
"cat3" => "product"
]
]
]


My Answer:
To achieve this nested array structure dynamically, you can modify your loop to create nested arrays based on the folders in the $explode array. Here's an updated version of your code:

php
$folder = [];
$lastKey = null;

$explode = explode("/", $product->folder);

foreach($explode as $key => $value) {
if($lastKey === null) {
$folder[$value] = 'test';
} else {
$folder[$lastKey] = [$value => 'test'];
}
$lastKey = $value;
}

dd($folder);


This code will create a nested array based on the folders in the $product->folder string. It will check if the current folder has a parent folder and create the nested structure accordingly.

Rate this post

3 of 5 based on 7601 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us