php foreach有一个和很多元素

时间:2013-05-09 05:38:33

标签: php arrays loops foreach

例如我有这样的代码,我正在做foreach循环,它工作正常

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

$ response的内容是

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

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

            )
    )

但是,当$ response的源只包含一个元素时,我有这样的代码,而foreach循环将不起作用。

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

            )
    )

所以问题是如何让它以最小的变化发挥作用。请原谅我的初学英语。

3 个答案:

答案 0 :(得分:1)

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

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

这样可行,但理想情况下你的数组应如下所示:

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

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

)

就这样,即使还有一个你可以预见它。

答案 1 :(得分:1)

最好保持输入数组$ response的一致结构以使用单循环,否则你可以尝试跟随。

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

答案 2 :(得分:1)

试试这样..

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