提问人:Developer 提问时间:11/3/2023 最后编辑:BarmarDeveloper 更新时间:11/4/2023 访问量:34
使用 foreach 和 for 循环创建多维数组
Create multidimensional array using a foreach and for loop
问:
[
{
"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
答:
0赞
Barmar
11/3/2023
#1
不要在内循环中打印系列,它应该在外循环中打印。内部循环遍历包含国家/地区的键,并包含第三个循环,用于循环访问数组键以打印国家/地区名称。
$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>";
}
0赞
Pippo
11/4/2023
#2
另一个可能的解决方案:
foreach ($json_data as $rowId => $row) {
echo ($rowId > 0 ? '<br>' : ''), ucfirst($row['Sports']['Series']), '<br>';
foreach (end($row) as $key => $val) {
echo $key, '<br>';
}
}
评论
$keys
$json_data
$json_data[$i]
CricketTeams
menuItems