搜索特定键的多维数组并输出其数据

时间:2012-04-20 21:19:05

标签: php arrays loops multidimensional-array foreach

我有以下数组构造:$array[$certain_key][some_text_value]

在while循环中,我想打印数组中的数据,其中$certain_key是特定值。

我知道如何遍历多维数组,这不是解决此问题的完整方法:

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

我不希望每次都循环整个数组,但只有在$certain_key匹配时才会循环。

编辑:更确切地说,这就是我要做的事情:

$array[$array_key][some_text];

while reading from db {

  //print array where a value returned from the db = $array_key

}

5 个答案:

答案 0 :(得分:2)

while ($row = fetch()) {
   if (isset($array[$row['db_id']])) {
      foreach ($array[$row['db_id']] as $some_text_value => $some_text_values_value) {
         echo ...
      }
   }
}

答案 1 :(得分:1)

foreach ($array as $certain_key => $value) {
    if($certain_key == $row['db_id']) {
        foreach ($value as $some_text_value) {
            echo "$v2\n";
        }
    }
}

答案 2 :(得分:1)

你的意思是

foreach($array[$certain_key] as $k => $v)
{
     do_stuff();
}

答案 3 :(得分:0)

也许您正在寻找array_key_exists?它的工作原理如下:

if(array_key_exists($certain_key, $array)) {
   // do something
}

答案 4 :(得分:0)

<?php

foreach ($a as $idx => $value) {
    // replace [search_value] with whatever key you are looking for
    if ('[search_value]' == $idx) {
        // the key you are looking for is stored as $idx
        // the row you are looking for is stored as $value
    }
}