使用array_reverse PHP反转对象

时间:2018-04-20 23:15:24

标签: php arrays xml foreach rss

我正在尝试处理RSS Feed,但是想要反向执行,以便最后导入最新项目以保持订单正确。

#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
class Person
{
private:
    int idNum;
    string name;
public:
    Person(const int, const string);
    friend ostream& operator<<(ostream&, const Person&);
};
Person::Person(const int id, const string nm)
{
    idNum = id;
    name = nm;
}
ostream& operator<<(ostream& out,const Person& p)
{
    out << p.name << p.idNum;
    return out;
}
ostream& personDisplay(ostream& s)
{
    cout.setf(ios::left);
    cout.width(12);
    return s;
}
int main()
{
    const int MAX = 10;
    Person p[MAX];
    int id;
    string name;
    int x = 0;
    const int QUIT = 0;
    cout << "Enter an ID number or " << QUIT << " to quit ";
    cin >> id;
    while(id != QUIT && x < MAX)
    {
        cout << " Enter name ";
        cin >> name;
        p[x] = Person(name, id);
        ++x;
        cout << "Enter an ID number or " << QUIT << " to quit ";
        cin >> id;
    }
    for(x = 0; x < count; ++x)
    {
        cout << personDisplay << p[x];
        if(x % 2 == 1)
            cout << endl;
        cout << "   ";
    }
    cout << endl;
    return 0;
}

然而,只有抛出$content = file_get_contents($feed_url); $rss = new SimpleXmlElement($content); $rss = array_reverse($rss); foreach($rss->channel->item as $entry) { echo $entry->title; } &amp; array_reverse() expects parameter 1 to be array错误。我怎样才能反转数组,以便每个数组都向后工作?

1 个答案:

答案 0 :(得分:1)

$rss->channel->itemSimpleXMLElement对象,而不是数组。您可以使用foreach进行迭代,但其他数组操作将无效。

如果你想反向迭代,得到计数,然后通过索引访问每个元素,将索引计算下来。

$items = $rss->channel->item;
$count = count($items);
for ($i = $count-1; $i >= 0; $i--) {
    echo $items[$i]->title;
}