1

I have following array construction: $array[$certain_key][some_text_value]

And in a while loop, I want to print the data from the array, where $certain_key is a specific value.

I know how to loop through multidimensional arrays, which is not the complete solution to this problem:

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

I do not want to loop the whole array each time, but only when $certain_key is matched.

EDIT: to be more exact, this is what I'm trying to do:

$array[$array_key][some_text];

while reading from db {

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

}
2
  • You got a lot of possible solutions, each is valid for different situations. You should be more precise with your questions to narrow down the answers you receive. Commented Apr 20, 2012 at 21:25
  • @Benjamin: ok, thank you... I will update it now... did not expect so much help so quickly! Commented Apr 20, 2012 at 21:28

5 Answers 5

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
  • omg... thank you! this looks very promising, I will try it! Thank you for a practical sample!! Commented Apr 20, 2012 at 21:22
1
foreach ($array as $certain_key => $value) {
    if($certain_key == $row['db_id']) {
        foreach ($value as $some_text_value) {
            echo "$v2\n";
        }
    }
}
0
1

You mean like

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

?

1
  • Are you checking to see if the key exists? Look at array_key_exists(). Commented Apr 20, 2012 at 21:25
0

Maybe you're looking for array_key_exists? It works like this:

if(array_key_exists($certain_key, $array)) {
   // do something
}
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
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.