Jurager
Jurager

Reputation: 45

php foreach with one and a lot elements

For example I have code like this, I'm doing foreach loop and it works fine

foreach ( $response['albums']['album'] as $key=>$album ) { 
    echo($album['artist']['name']);
}

The content of $response is

[albums] => Array
    (
        [album] => Array
            (
                [0] => Array
                    (
                        [name] => Recovery
                        [playcount] => 1176206
                    )

                [1] => Array
                    (
                        [name] => The Eminem Show
                        [playcount] => 948632
                    )

            )
    )

But, when the source of $response consist only from one element, i have such code, and foreach loop will not work.

[albums] => Array
    (
        [album] => Array
            (
                [name] => Doo-Wops & Hooligans
                [playcount] => 1106732

            )
    )

So the question is how to let it work with minimal changes. Please excuse me for my beginner English.

Upvotes: 0

Views: 235

Answers (3)

Prasath Albert
Prasath Albert

Reputation: 1457

Try like this..

if(array_key_exists(0,$response['albums']['album']))
{
        foreach ( $response['albums']['album'] as $key=>$album ) { 
        echo($album['artist']['name']);
    }
}
else
{
        foreach ( $response['albums']['album'] as $album ) { 
        echo $album['name'];
    }
}

Upvotes: 1

Ganesh Bora
Ganesh Bora

Reputation: 1153

it will be better to keep consistent structure of input array $response to use single loop otherwise you can try following.

if(count($response['albums']) == 1){
 foreach($response['albums'] as $key =>$val) {

         echo $val['album']['name'];
   }
}
else {
foreach ( $response['albums']['album'] as $key=>$album ) { 
    echo($album['artist']['name']);
}
}

Upvotes: 1

We0
We0

Reputation: 1149

foreach ( $response['albums'] as $album ) { 

    if(isset(album['name']))
    {   
        echo $album['artist']['name'];
    }
    else
    {
        foreach($album as $val)
        {
            echo $val['artist']['name'];
        {
    }
}

That will work, although ideally your array should look like:

[albums] => Array
(
    [0] => Array
        (
            [name] => Recovery
            [playcount] => 1176206
        )

    [1] => Array
    (
        [name] => The Eminem Show
        [playcount] => 948632
    )

)

That way even if there is still one you can foreach it.

Upvotes: 1

Related Questions