[英]PHP Looping through a multi-dimensional array
嗨我在PHP中有這個多維數組:
$team_arrays = array (
"lakers" => array (
24 => "Bryant",
6 => "Price",
17 => "Lin"
),
"knicks" => array (
7 => "Anthony",
22 => "Shumpert",
12 => "Jackson"
),
"thunder" => array (
35 => "Durant",
0 => "Westbrook",
13 => "Miller"
)
);
我想要顯示如下內容:
球隊名稱:湖人隊
球隊名稱:尼克斯隊
...
這是我嘗試但似乎不起作用的代碼:
foreach ($team_arrays as $names => $team) {
echo "<h2>Team Name: " . $names . "</h2>";
echo "<ol>";
foreach ($team_arrays as $jersey => $names) {
echo "<li>" . $names . " = " . $jersey . "</li>";
}
echo "</ol>";
}
它會產生這種錯誤
Notice: Array to string conversion in
有人會試圖尋求幫助。 請。
我從其他問題中找到了這個解決方案 ,但似乎我無法與之相關。
您的代碼中只有一個小問題
foreach ($team_arrays as $jersey => $names) {
^ // again looping over the same outer array?
那個內循環是錯誤的,你應該遍歷$team
而不是$team_arrays
因為你的外循環使用$team
變量來獲取每個團隊。
foreach ($team as $jersey => $names) {
其余的代碼和邏輯已經很好了。
您需要更改此行;
foreach ($team_arrays as $jersey => $names) {
至:
foreach ($team as $jersey => $names) {
改為foreach ($team as $jersey => $names)
嘗試這個 :
$team_arrays = array (
"lakers" => array (
24 => "Bryant",
6 => "Price",
17 => "Lin"
),
"knicks" => array (
7 => "Anthony",
22 => "Shumpert",
12 => "Jackson"
),
"thunder" => array (
35 => "Durant",
0 => "Westbrook",
13 => "Miller"
)
);
foreach ($team_arrays as $names => $team) {
echo "<h2>Team Name: " . $names . "</h2>";
echo "<ol>";
foreach ($team as $jersey => $names) {
echo "<li>" . $names . " = " . $jersey . "</li> \n";
}
echo "</ol>";
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.