Ryan Hipkiss Ryan Hipkiss - 11 months ago 59
PHP Question

Loop over one array as if it was a multidimensional array

I have an array like:

$array = array(
'name' => 'Humphrey',
'email' => 'humphrey@wilkins.com

This is retrieved through a function that gets from the database. If there is more than one result retrieved, it looks like:

$array = array(
[0] => array(
'name' => 'Humphrey1',
'email' => 'humphrey1@wilkins.com'
[1] => array(
'name' => 'Humphrey2',
'email' => 'humphrey2@wilkins.com'

If the second is returned, I can do a simple
foreach($array as $key => $person)
, but if there is only one result returned (the first example), I can't run a foreach on this as I need to access like:
within the foreach loop.

Is there any way to make the one result believe its a multidimensional array?

Answer Source

Try this :

if(!is_array($array[0])) {
    $new_array[] = $array;
    $array = $new_array;