搜索多维数组并返回父键

时间:2014-09-17 11:21:13

标签: php arrays search multidimensional-array key

我有一个多维数组$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中每个游戏都有的关键字。)

现在,我想找出包含键game-one的此值的数组的示例game-twodownload_id。这很有效。

我在下面的代码中做的是迭代$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.");

?>

我希望你能理解我的问题,并能帮助我。我非常感激......我真的被困在这里了。

1 个答案:

答案 0 :(得分:2)

如果你已经知道你将在download_id中搜索,那么你使这段代码变得比它需要的复杂得多。除了尝试完全不同的方法之外,我不确定你的问题是否真的可以解答。

您可以直接查看您知道自己要查找的列的值,而不是使用所有这些array_search调用,如下所示:

  foreach( $games_array as $game_id => $game_data ) {
    if( $game_data["download_id"] == $search_for_value ) {
      $file = $game_data["file"];
      break;
    }
  }