如何获取大型数组的所有对象的值并将它们设置为变量?

时间:2012-01-11 00:34:07

标签: php arrays multidimensional-array

我是PHP的新手。我必须用这种语言编写类似RSS Reader的系统。所以我解析了XML文件(它们是RSS Feeds)并获得了一个包含许多子数组的大型数组。由于很难解释我的需求,我决定添加示例代码。
 如您所见,我的大型数组中有一个 items ,并且有很多 items 数组的子数组,例如, [0] [1] [2] [3] 依此类推。 (我在示例中添加了其中两个 - [0] [1]

Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [title] => First title
                    [alternate] => Array
                        (
                            [0] => Array
                                (
                                    [href] => http://example-one.com/first-title/
                                )
                        )

                    [contents] => Array
                        (
                            [content] => First content
                        )
                    [author] => First author
                    [origin] => Array
                        (
                            [htmlUrl] => http://example-one.com
                        )

                )

            [1] => Array
                ( 
                    [title] => Second title
                    [alternate] => Array
                        (
                            [0] => Array
                                (
                                    [href] => http://example-two.com/second-title/
                                )
                        )

                    [contents] => Array
                        (
                            [content] => Second content
                        )

                    [author] => Second author

                    [origin] => Array
                        (
                            [htmlUrl] => http://example-two.com
                        )

                )

        )

)

所以我需要获取输出中所有对象的值,并将它们设置为循环中的变量。例如,此数组的输出必须如下:

title = First title
href = http://example-one.com/first-title/
content = First content
author = First author
htmlUrl = example-one.com


title = Second title
href = http://example-two.com/second-title/
content = Second content
author = Second author
htmlUrl = example-two.com

因为我是PHP的初学者,所以编写逻辑代码很难。如果您有任何解决此问题的想法,请回答。 提前谢谢!

1 个答案:

答案 0 :(得分:2)

您应该检查this link。它告诉我们如何处理像树一样结构化的数组。尽管它可能看起来有点先进和复杂,但要尝试理解它。相信我,这对你来说是最好的!

修改

$a = array(); // This is the array that we will store the values

function traverse($array)
{
    global $a;

    $results = array();

    foreach($array as $key => $value) { 

         if (is_array($value)) { 
            $results = traverse($value); // This is where you make the function recursive and go deeper in the array
         } else { 
            $a[] = $key . ' = ' . $value; // This is where you store the values
         }

    }

    return $a;
}
// You just call the function like this.
$ret = traverse($arr);

echo implode('<br>', $ret);