使用PHP将项目循环并计数到多维数组中

时间:2019-04-14 20:16:33

标签: php arrays

我有这个数组:

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
                )
        )
)

我想深入了解它,并回显每个国家(美国和中国)的count项目。

所以我的尝试是这样的:

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

    foreach ($value as $subkey => $subvalue) {
        echo $value." -> ".$subvalue['Name']." make ".$subvalue['Item']."<br />";    
    }
}

1 个答案:

答案 0 :(得分:2)

您可以这样做:

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

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

使用有意义的名称保留变量可以使生活更轻松