我有一个这样的数组:
$games_array = array(
"game-one-id" => array(
array("name" => "Game One"),
array("url" => "game-one-url"),
array("asd" => "asdfg")
),
"game-two-id" => array(
array("name" => "Game Two"),
array("url" => "game-two-url"),
array("asd" => "asdfg")
)
);
我希望列出$games_array
中的所有游戏并打印每个游戏的一些属性,例如其网址。
这就是我提出的,但没有打印出来:
foreach ($games_array as $game_id => $game_data) {
echo '
<table><tr>
<td><a href="http://www.example.com/game/' . $game_data["url"] . '/">' . $game_data["name"] . '</a></td>
</tr></table>
';
}
有人可以帮助我吗
答案 0 :(得分:1)
该循环与这样的数组相关
$games_array = array(
"game-one-id" => array(
"name" => "Game One",
"url" => "game-one-url",
"asd" => "asdfg"
),
"game-two-id" => array(
"name" => "Game Two",
"show_compatibility" => "game-two-url",
"asd" => "asdfg"
)
);
尝试! :)
答案 1 :(得分:0)
使用您正在使用的$game_array
,您应该使用:
foreach ($games_array as $game_id => $game_data) {
echo '
<table><tr>
<td><a href="http://www.example.com/game/' . $game_data[1]["url"] . '/">' . $game_data[0]["name"] . '</a></td>
</tr></table>
';
}
变量$game_array
应为:
$games_array = array(
"game-one-id" => array(
"name" => "Game One",
"url" => "game-one-url",
"asd" => "asdfg"
),
"game-two-id" => array(
"name" => "Game Two",
"show_compatibility" => "game-two-url",
"asd" => "asdfg"
)
);
如果您想使用:
foreach ($games_array as $game_id => $game_data) {
echo '
<table><tr>
<td><a href="http://www.example.com/game/' . $game_data["url"] . '/">' . $game_data["name"] . '</a></td>
</tr></table>
';
}
答案 2 :(得分:0)
尝试此操作而不更改数组格式。
<?php
$games_array = array(
"game-one-id" => array(
array("name" => "Game One"),
array("url" => "game-one-url"),
array("asd" => "asdfg")
),
"game-two-id" => array(
array("name" => "Game Two"),
array("url" => "game-two-url"),
array("asd" => "asdfg")
)
);
foreach ($games_array as $game_id => $game_data) {
//var_dump($game_data);
echo '
<table><tr>
<td><a href="http://www.example.com/game/' . $game_data[1]["url"] . '/">' . $game_data[0]["name"] . '</a></td>
</tr></table>
';
}
?>
将数组格式更改为
$games_array = array(
"game-one-id" => array(
"name" => "Game One",
"url" => "game-one-url",
"asd" => "asdfg"
),
"game-two-id" => array(
"name" => "Game Two",
"show_compatibility" => "game-two-url",
"asd" => "asdfg"
)
);
答案 3 :(得分:-1)
应该是这样的:
foreach ($games_array as $game_id => $game_data) {
echo '
<table><tr>
<td><a href="http://www.example.com/game/' . $game_data["url"] . '/">' . $game_data[0]["name"] . '</a></td>
</tr></table>
';
}
您指定为子游戏-id-id的每个数组都没有键。默认情况下,它将从0开始为一个键,并且每次上升1。我想你可能宁愿这样做:
$games_array = array(
"game-one-id" => array("name" => "Game One","url" => "game-one-url","asd" => "asdfg")
);
foreach ($games_array as $game_id => $game_data) {
echo '
<table><tr>
<td><a href="http://www.example.com/game/' . $game_data["url"] . '/">' . $game_data["name"] . ' - ' . $game_data["url"] . '</a></td>
</tr></table>
';
}