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

And in a while loop (reading from db) I want to print the data from the array, where $row['db_id'] = $certain_key.

So, I did not figure out how to do this with the php.net explanation of looping through multidimensional arrays:

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

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

Hope it was clear enough. Thank you for every help!


EDIT: to me more exact, I hope... this is what I try to do:

$array[$array_key][some_text];

while reading from db {

//print array where $db_id = $array_key

}
link|improve this question

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. – Benjam 16 hours ago
@Benjamin: ok, thank you... I will update it now... did not expect so much help so quickly! – Chris 16 hours ago
feedback

5 Answers

up vote 1 down vote accepted
foreach ($array as $certain_key => $value) {
    if($certain_key == $row['db_id']) {
    foreach ($value as $some_text_value) {
        echo "$v2\n";
    }
    }
}
link|improve this answer
thx, your solution was the easiest to implement, finally :) – Chris 16 hours ago
feedback
<?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
    }
}
link|improve this answer
feedback

You mean like

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

?

link|improve this answer
yes, exactly... but this gives me an error for invalid argument in foreach... – Chris 16 hours ago
Are you checking to see if the key exists? Look at array_key_exists(). – SenorAmor 16 hours ago
feedback
while ($row = fetch()) {
   if (isset($array[$row['db_id']])) {
      foreach ($array[$row['db_id']] as $some_text_value => $some_text_values_value) {
         echo ...
      }
   }
}
link|improve this answer
omg... thank you! this looks very promising, I will try it! Thank you for a practical sample!! – Chris 16 hours ago
feedback

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

if(array_key_exists($certain_key, $array)) {
   // do something
}
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.