0

I've this array:

Array
(
    [USA] => Array
        (
            [0] => Array
                (
                    [Name] => Apple
                    [Item] => Phones and Computers
                )
            [1] => Array
                (
                    [Name] => McDonalds
                    [Item] => Food
                )

        )
    [China] => Array
        (
            [0] => Array
                (
                    [Name] => Lenovo
                    [Item] => Computers
                )
        )
)

I would like to loop into it and echo the count of items for each country (USA and China).

So my try was this one:

foreach ($arr as $key => $value) {
    echo count($arr[$value]);
    echo '<br />';

    foreach ($value as $subkey => $subvalue) {
        echo $value." -> ".$subvalue['Name']." make ".$subvalue['Item']."<br />";    
    }
}
3
  • And what is wrong? Commented Apr 14, 2019 at 20:17
  • 2
    You don't need the echo count($newArr[$value]); just echo count($value);. And you can not echo $value in the second loop as it is array and not a string Commented Apr 14, 2019 at 20:19
  • @dWinder $key should be outputted instead. Commented Apr 14, 2019 at 20:24

1 Answer 1

2

You can do this:

foreach ($arr as $country => $companies) {
    echo $country . " has " . count($companies) . " item <br />";

    foreach ($companies as $k => $company) {
        echo $company['Name'] . " make " . $company['Item']."<br />";    
    }
}

Keep your variable with meaningful name can make life much easier

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

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.