我是PHP的新手。我必须用这种语言像RSS Reader一样编写系统。所以我解析了XML文件(这是RSS提要(,并得到了一个包含许多子数组的大型数组。由于很难解释我需要什么,我决定添加示例代码。
如您所见,我的大数组中有一个items
,并且有很多items
数组的子数组,例如 [0]
、 [1]
、 [2]
、 [3]
等。(我只在示例中添加了其中的 2 个 - [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的初学者,所以很难编写逻辑代码。如果您有解决此问题的任何想法,请回答。提前感谢!
您应该检查此链接。它告诉如何处理像树一样结构的数组。尽管它看起来有点先进和复杂,但请尝试理解它。相信我,这对你来说是最好的!
编辑
$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);