Jump to content

[SOLVED] How do I iterate over array of associative arrays?


devdavad

Recommended Posts

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.

<?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'];
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.