使用 foreach 和 for 循环创建多维数组

问题描述 投票:0回答:1
[
{
    "Sports":
    {
        "Series": "Wordlcup"
    },
    "CricketTeams":
    {
        "India": "india.com",
        "Australia": "australia.com",
        "England": "england.com",
    }
},
{
    "Sports":
    {
        "Series": "Places"
    },
    "CricketTeams":
    {
        "Pune": "/pune",
        "Delhi": "/delhi",
        "Ranchi": "/ranchi/"
    }
},
{
    "Sports":
    {
        "Series": "man of the match"
    },
    "menuItems":
    {
        "Rohit": "rohit.com",
        "Kohli": "kohli.com"
    }
}]
for($i = 0; $i < count($json_data); $i++) {
    echo "<br>";
    foreach($json_data[$keys[$i]] as $item => $name) {
        echo $name['Series'];
    }
}

数据来自 Json 文件,所以我在这里使用 json-data 我得到的输出为:

Worldcup
places
Man of the match

但我需要如下输出:

Worldcup 
India
Australia
England

Places
Pune
Delhi
Ranchi

Man of the match
Rohit
Kohli
php arrays for-loop multidimensional-array foreach
1个回答
0
投票

不要在内循环中打印系列,应该在外循环中打印。内部循环迭代包含国家/地区的键,并且它包含第三个循环来迭代数组键以打印国家/地区名称。

$keys = ['CricketTeams', 'menuItems'];
foreach ($json_data as $item) {
    echo "{$item['Sports']['Series']}<br>";
    foreach ($keys as $key) {
        if (isset($item[$key])) {
            foreach (array_keys($item[$key]) as $country) {
                echo "$country<br>";
            }
        }
    }
    echo "<br>";
}
© www.soinside.com 2019 - 2024. All rights reserved.