使用foreach的数组中的多数组

I'm using foreach to echo array multidimensional array.

I know there have another simple way but I want to try using foreach.

here is my code:

<?php
$cars = array(
    array("Volvo", 22, 18),
    array("BMW", 15, 13, 
        array(
            'satu' => 'heelo'
        )
    ),
    array("Saab", 5, 2),
    array("Land Rover", 17, 15, 
        array('satu','dua')
    )
);

foreach ($cars as $kebal)
{
    if (is_array ($kebal))
    {
        foreach ($kebal as $katak)
        {
            echo($katak);
            echo "<br>";
            echo "<br>";            
        }
    }
    else
    {
        echo ($kebal);
        echo "<br>";    
    }
}
?>

and the output i get is :

Volvo

22

18

BMW

15

13


Notice: Array to string conversion in C:\xampp\htdocs\latihtubi\dataarray.php on line 42
Array

Saab

5

2

Land Rover

17

15


Notice: Array to string conversion in C:\xampp\htdocs\latihtubi\dataarray.php on line 42
Array

so, how to properly write the code? Thanks.

...but I want to try using foreach.

Ok - the reason your code isn't quite working is that when you reach the array e.g. satu => heelo you're just trying to echo it, because you aren't handling it at that point.

Just add another foreach to the outside:

foreach ($cars as $carOptions) {
    foreach ($carOptions as $kebal) {
        if (is_array($kebal)) {
            foreach ($kebal as $katak) {
                echo $katak;
                echo "<br>";
                echo "<br>";            
            }
        } else {
            echo $kebal;
            echo "<br>";
        }
    }
}

The problem you're having is most of the elements of your array are either strings or integers, but you also have 2 elements that are arrays. You're best bet is to test if the value is an array first, then decide what to do.

<?php
    $cars = array(
        array("Volvo",22,18),
        array("BMW",15,13,array('satu'=>'heelo')),
        array("Saab",5,2),
        array("Land Rover",17,15,array('satu','dua'))
    );

    function myLoop($inputData){
        if( is_array($inputData) ){
            foreach($inputData as $value){
                myLoop($value);
                echo "<br>";
            }
        } else {
            echo "$inputData<br>";
        }
    }

    myLoop($cars);
?>