Skip to content
Advertisement

Array inside arrays of arrays

I need help, I can’t assign the single values of the array inside the array of the array to a variable.

$arr_categories = array(
    array(1,"category_1",

            01=>"product name 1", 20 . "€"=> "description 1.",
            02=>"product name 2", 25 . "€"=> "description 2.",
            03=>"product name 3", 12 . "€"=> "description 3.",
            04=>"product name 4", 33 . "€"=> "description 4.",
            05=>"product name 5", 36 . "€"=> "description 5.",
        
    ),
    array(2,"category_2",

            01=>"product name 1", 20 . "€"=> "description 1.",
            02=>"product name 2", 25 . "€"=> "description 2.",
            03=>"product name 3", 12 . "€"=> "description 3.",
            04=>"product name 4", 33 . "€"=> "description 4.",
            05=>"product name 5", 36 . "€"=> "description 5.",
    
    ), 
    array(3,"category_3",

            01=>"product name 1", 20 . "€"=> "description 1.",
            02=>"product name 2", 25 . "€"=> "description 2.",
            03=>"product name 3", 12 . "€"=> "description 3.",
            04=>"product name 4", 33 . "€"=> "description 4.",
            05=>"product name 5", 36 . "€"=> "description 5.",
      
    )
);

I could assign the values of the second dimension array to single variables like this:

for ($i=0;$i<count($arr_categories);$i++){
    $category = $arr_categorie[$i];
    $category_id = $category[0];
    $category_name = $category[1];

But how can I use a second loop to count and extract the single values of the products?I have tried with a second “for” loop,”foreach”, but nothing was working. Does someone have suggestions? Is it possible I have to modify the sintax of my multidimensional array?

I hope you can help, thank you! 🙂

Advertisement

Answer

I suggest you add another level of nesting, putting all the products in their own array, rather than in the category array itself. In addition, you can make the inner arrays associative rather than hard-coding specific positions.

And your innermost array also needs better structuring. I can’t understand why you would use the price as a key that returns the description. You should have separate keys for price and description.

$arr_categories = array(
    array('id' => 1,
          'name' => "category_1",
          'products' => array(
            array('name' => "product name 1", 'price' => "20€", 'description' => "description 1."),
            array('name' => "product name 2", 'price' => "25€", 'description' => "description 2."),
            ...
          )
    ),
    ...
);

Then your loop can be:

foreach ($arr_categories as $category) {
    $category_id = $category['id'];
    $category_name = $category['name'];
    $category_products = $category['products'];
    ...
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement