php - Creating a nested array dynamically with for loop

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 thiscat1/cat2/cat3
then the array would looks like this
[
"cat1" => [
"cat2" => [
"cat3" => "product"
]
]
]
Answer
Solution:
You can build nested array using JSON string and convert into array usingjson_decode
$path = 'cat1/cat2/cat3/cat4/product';
$folders = explode('/',trim($path,'/'));
$last = array_pop($folders);
$folders = str_replace(': []',': "'.$last.'"',
array_reduce(array_reverse($folders),function($carry,$item) {
if($carry) {
return '{"'.$item.'": '.$carry.'}';
}
return '{"'.$item.'": []}';
})
);
$folders = json_decode($folders,true);
// Test
print_r($folders);
and it will be result as :
Array
(
[cat1] => Array
(
[cat2] => Array
(
[cat3] => Array
(
[cat4] => product
)
)
)
)
and formatted result
[
"cat1" => [
"cat2" => [
"cat3" => [
"cat4" => "product"
]
]
]
]
Answer
Solution:
Simple solution for your problem
$path = 'cat1/cat2/cat3/product';
$folder = [];
$explode = explode("/", $path);
for($i = 0; $i < count($explode)-1; $i++)
{
if($i+1 >= count($explode)-1)
$folder[$explode[$i]] = $explode[$i+1];
else
$folder[$explode[$i]] = '';
}
print_r($folder) result will be this
Array ( [cat1] => [cat2] => [cat3] => product )
Answer
Solution:
Please try the following.
// Add product title first.
$folder = end($explode);
// Iterate over categories to create a nested array.
for ($counter = count($explode) - 2; $counter >= 0; $counter--) {
$folder = [$explode[$counter] => $folder];
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.