0

I have a multidimensional array

array:2 [▼
    "lamborghini" => array:1 [▼
        "cars" => array:5 [▼
          0 => "1"
          1 => "4"
          2 => "2"
          3 => "5"
          4 => "7"
        ]
      ]
    "ferrari" => array:1 [▼
        "cars" => array:1 [▼
          0 => "8"
        ]
      ]
    ]

I tried to achieve the possible output like this

Lamborghini
1 4 2 5 7

ferrari
8

I tried this method

foreach($cars as $car)
{
    foreach($car as $product)
    {
        for($i=0; $i<count($product); $i++)
        {
            echo $product[$i];
        }
    }
}

And output that I achieved is this

142578

Can anyone help me achieving the possible output? It should also print the first array name. eg

lamborghini
1 4 2 5 7

3 Answers 3

1

Try this:

$cars = [
    'lamborghini' => [
        'cars' => [1, 2, 3, 4],
    ],
    'ferrari' => [
        'cars' => [1],
    ],
];

foreach($cars as $make => $cars) {
    echo $make . "<br>";
    foreach($cars as $models) {
        echo implode(' ', $models) . "<br>";
    }
}

I don't know how you want to display the results but you can remove the . <br> tags.

Sign up to request clarification or add additional context in comments.

1 Comment

I will take care of the result. Yess this is what I wanted thank you :)
0

You could do this instead

<?php 
foreach($car as $fer){
    foreach($cars as $lamb) {
      echo "Lamborghini: ".$lamb;
    }
   echo "Ferrari: ".$fer;
}
?>

This way it will loop first the lamb and then the ferrari next

2 Comments

What if other manufacturers kick-in, then I always have to change the foreach loop. I want one general method that would print the first array then second then third until there aren't arrays anymore
Also if you see that first it should give the name of the array lamborghini then print its elements
0

This will get you desired output:

foreach($car as $car_k => $car)
{
 foreach($car as $product => $num_car)
 {
    echo $car_k. ':' .implode(',',$num_car);
    echo "<br/>"

 }
}

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.