devdavad Posted January 24, 2009 Share Posted January 24, 2009 I have a an array of associative arrays fetched from the fetchAll PDO method. So the structure looks kind of like: array -> array -> ('name' => 'john', 'lastname => 'doe') array ->('name' => 'jane', 'lastname' => 'doe') I was wondering how I could iterate over all of the elements in the array using foreach. I originally was thinking of an embedded foreach loop like: foreach($arrayoarrays as $key => $val) { foreach($whatwouldIcallthis as $key2 => $val2) { } } but I'm not for sure of the syntax I would use to tell the first foreach to iterate over the arrays in the array returned from the PDO function and the encapsulated foreach to iterate over the values in the current array that the first foreach is iterating over. Quote Link to comment https://forums.phpfreaks.com/topic/142292-solved-how-do-i-iterate-over-array-of-associative-arrays/ Share on other sites More sharing options...
DeanWhitehouse Posted January 24, 2009 Share Posted January 24, 2009 I would do <?php $i = 0; $array = array(array("test"),array("test2")); foreach($array as $new_array) { echo $array[$i]; $i++; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/142292-solved-how-do-i-iterate-over-array-of-associative-arrays/#findComment-745495 Share on other sites More sharing options...
genericnumber1 Posted January 24, 2009 Share Posted January 24, 2009 <?php foreach($arrayoarrays as $key => $val) { foreach($val as $key2 => $val2) { // Whatever } } ?> Or if you prefer... (what I would do) <?php foreach($arrayoarrays as &$name) { echo $name['name'] . ' ' . $name['lastname']; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/142292-solved-how-do-i-iterate-over-array-of-associative-arrays/#findComment-745570 Share on other sites More sharing options...
DeanWhitehouse Posted January 24, 2009 Share Posted January 24, 2009 O, i didn't see the custom keys, just modify mine by removing the counter and the $i var and replace the $i in the echo with the key name Quote Link to comment https://forums.phpfreaks.com/topic/142292-solved-how-do-i-iterate-over-array-of-associative-arrays/#findComment-745574 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.