0

例如我有这样的代码,我正在做 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

            )
    )

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

4

3 回答 3

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
    )

)

这样,即使还有一个你可以foreach它。

于 2013-05-09T05:50:41.137 回答
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']);
}
}
于 2013-05-09T05:51:56.467 回答
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'];
    }
}
于 2013-05-09T05:55:37.260 回答