如何使用foreach循环获取此数组

时间:2011-11-05 20:50:10

标签: php arrays foreach fetch

我有一个多维数组。通过使用curl解析xml返回数组。当curl给我输出时,我使用$ array =(array)simplexml_load_string($ query)将输出转换为数组;并且$ array在下面给出。现在我想使用foreach循环获取此数组,并希望从此数组中获取所有内容

Array
(
[Meta] => SimpleXMLElement Object
    (
      [Query] => php programming
      [ResultOffset] => SimpleXMLElement Object
            (
            )

      [NumResults] => 25
      [TotalResults] => 36839
    )

[Slideshow] => Array
       (
        [0] => SimpleXMLElement Object
            (
                [ID] => 1966058
                [Title] => title here
                [Description] => description here
                [Status] => 2
                [Username] =>usrname
                [URL] => url here
                [ThumbnailURL] => a url
                [ThumbnailSmallURL] => a url
                [Embed] => some embed code
    )
    [1] => SimpleXMLElement Object
            (
                [ID] => 1966058
                [Title] => title here
                [Description] => description here
                [Status] => 2
                [Username] =>usrname
                [URL] => url here
                [ThumbnailURL] => a url
                [ThumbnailSmallURL] => a url
                [Embed] => some embed code
    )

并继续

2 个答案:

答案 0 :(得分:2)

您可以在不使用foreach的情况下检索元信息:

echo $array['Meta']->Query;
echo $array['Meta']->NumResults;

依旧......

要获取幻灯片:

foreach($array['Slideshow'] as $slideshow)
{
    echo $slideshow->ID;
    echo $slideshow->Title;
    //-- and so on...
}

答案 1 :(得分:1)

如果要检索每个SimpleXMLElement对象的ID和标题,请尝试以下操作:

<?php
forach ($array['Slideshow'] as $simpleXMLelem) {
  echo $simpleXMLelem->getId();
  echo $simpleXMLelem->getTitle();
}