【发布时间】:2014-11-11 09:46:45
【问题描述】:
我有一个多维数组$games_array,看起来像这样:
<?php
$games_array = array(
"game-one" => array(
"name" => "Game One",
"download_id" => "gameone",
"file" => "./games/files/Game One.zip"
),
"game-two" => array(
"name" => "Game Two",
"download_id" => "gametwo",
"file" => "./games/files/Game Two.zip"
)
);
?>
例如,要访问第一个游戏的名称,我会使用 $games_array["game-one"]["name"],这样可以正常工作。
好的,现在来解决问题:我有一个值,例如gameone,它对应于download_id(这是$games_array 中每个游戏都有的键)。
现在我想找出包含键 download_id 的该值的数组的键,在此示例中为 game-one 或 game-two。这行得通。
我在下面的代码中所做的是遍历 $games_array 并搜索每个游戏的值(在下面的代码中 gameone)。如果找到,则返回该值的键。
接下来我要做的事情(if ($key_found) { ...)是通过使用我最初搜索的值所在的数组来尝试找出键file的值,并将其保存在$file .
很遗憾$file 总是空的,我不知道为什么。
<?php
$key = "";
$key_found = false;
$search_for_value = "gameone"; // search for game's download id in array
$file = "";
foreach($games_array as $game_id => $game_data) {
$key = array_search($search_for_value, $game_data);
echo "Searching for value <b>" . $search_for_value . "</b> in sub-array <b>" . $game_id . "</b>...<br />";
if ($key === FALSE) {
echo "Search returned FALSE<br /><br />";
} else if ($key === NULL) {
echo "Search returned NULL<br /><br />";
} else {
echo "\$key <b>" . $key . "</b> found! <br /><br />";
$key_found = true;
}
if ($key_found) {
// Key "download_id" found. Now search the parent array for the found key and use the
// returned result as the new key to access the "file" value in the found game's id in $games_array
$file = $games_array[array_search($key, $game_id)]["file"];
echo "The key <b>" . $key . "</b> was found.<br/>";
echo "\$file = " . $file . "<br />";
echo "Exiting loop.<br /><br />";
break;
}
}
$file = $games_array[$games_data]["file"];
echo "Checking if the file \"" . $file . "\" exists...<br />";
echo (file_exists($file) ? "File \"" . $file . "\" exists." : "File \"" . $file . "\" does not exist.");
?>
我希望你能理解我的问题并能帮助我。非常感谢......我真的被困在这里了。
【问题讨论】:
标签: php arrays search multidimensional-array key