0

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"
        ]
    ]
]
3
  • so the product value is the last element of array? Commented Jul 12, 2021 at 6:02
  • Yep it's the last one. Commented Jul 12, 2021 at 6:04
  • check out my answer Commented Jul 12, 2021 at 6:43

3 Answers 3

2

You can build nested array using JSON string and convert into array using json_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"
            ]
        ]
    ]
]
Sign up to request clarification or add additional context in comments.

Comments

0

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 )

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.