简体   繁体   English

使用PHP多维数组访问信息时遇到问题

[英]Trouble with accessing information in a multi-dimensional array in PHP

I'm trying to parse the most recent 3 news articles in an RSS feed. 我正在尝试在RSS feed中解析最近的3条新闻文章。 After that, it should create a "preview" of the description, and then display the title and the preview. 之后,它应该创建描述的“预览”,然后显示标题和预览。 I got it to display the first article 3 times... 我让它显示了3次第一篇文章...

<?php
$doc = new DOMDocument();
$doc->load('http://info.arkmediainc.com/CMS/UI/Modules/BizBlogger/rss.aspx?tabid=575593&moduleid=1167800&maxcount=25&t=16c4c7582db87da06664437e98a74210');
$arrFeeds = array();
foreach ($doc->getElementsByTagName('item') as $node) {
    $itemRSS = array ( 
        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
        'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
        'description' => $node->getElementsByTagName('description')->item(0)->nodeValue,
        'pubDate' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
    );
    array_push($arrFeeds, $itemRSS);
}
$itemRSS = array_slice($itemRSS, 0, 3); // This cuts it down to 3 articles.


for ($i = 0; $i < 3; $i++) 
{
    $title = $itemRSS['title'];
    $description = substr($itemRSS['description'],0,100);
    echo("<h2>".$title."</h2>");
    echo("<br />".$description."<br />");
}
?>

I also got it to "work" (show the first 3) by using a foreach loop... 我也通过使用foreach循环来使其“工作”(显示前三个)...

/*
foreach($itemRSS as $ira)
{
    $title = $itemRSS['title'];
    $description = substr($itemRSS['description'],0,100);
    echo("<h2>".$title."</h2>");
    echo("<br />".$description."<br />");
}
*/

It's commented out because it makes less sense to me. 已将其注释掉,因为它对我而言意义不大。

Please help! 请帮忙! Thanks! 谢谢!

You have pushed the rss items into the $arrFeeds and now you can access these by the index, eg $arrFeeds[0] would be the first rss item. 您已将rss项目推入$arrFeeds ,现在可以按索引访问这些项目,例如$arrFeeds[0]将是第一个rss项目。

for ($i = 0; $i < 3; $i++) 
{
  $title = $arrFeeds[$i]['title'];
  $description = substr($arrFeeds[$i]['description'],0,100);
  echo("<h2>".$title."</h2>");
  echo("<br />".$description."<br />");
}

But the following is better: with foreach : 但是以下更好: with foreach

$theFirstThreeArticles = array_slice($arrFeeds, 0, 3); // This cuts it down to 3 articles.

foreach($theFirstThreeArticles as $ira)
{
  $title = $ira['title'];
  $description = substr($ira['description'],0,100);
  echo("<h2>".$title."</h2>");
  echo("<br />".$description."<br />");
}

When you use foreach, there are there are two (in your case, but there can be 3) possible "parameters" that it accepts. 当您使用foreach时,有两个(就您而言,但可以是3个)它接受的可能的“参数”。 An array to traverse and a variable to store each element. 要遍历的数组和用于存储每个元素的变量。 This example: 这个例子:

$numbers = array('one', 'two');
foreach($numbers as $number) {
    echo "\nNew Iteration\n";
    var_dump($numbers);
    var_dump($number);
}

Will output : 将输出

New Iteration
array(2) {
  [0] => string(3) "one"
  [1] => string(3) "two"
}
string(3) "one"

New Iteration
array(2) {
  [0] => string(3) "one"
  [1] => string(3) "two"
}
string(3) "two"

The iterator never modifies the array. 迭代器从不修改数组。 It just sets $number to be the value of each element in the array until there are no more elements. 它只是将$number设置$number数组中每个元素的值,直到没有更多元素为止。 The same principle applies to a for loop. 相同的原理适用于for循环。 The code below will produce the same as above . 下面的代码将产生与上面相同的代码。

$numbers = array('one', 'two');
for($i = 0; $i < count($numbers); $i++) {
    echo "\nNew Iteration\n";
    var_dump($numbers);
    var_dump($numbers[$i]);
}

The same applies when you use multidimensional arrays. 使用多维数组时,也是如此。 Whether you choose for or foreach , you have to access each element in the array. 无论您选择for还是foreach ,都必须访问数组中的每个元素。 So your code will look something like this: 因此,您的代码将如下所示:

foreach($rssItems as $rssItem)
{
    $title = $rssItem['title'];
    $description = substr($rssItem['description'],0,100);
    echo("<h2>".$title."</h2>");
    echo("<br />".$description."<br />");
}

I chose to use foreach because I find it's much easier to let PHP handle the iteration. 我选择使用foreach,因为我发现让PHP处理迭代要容易得多。 Plus, the foreach line reads properly in English. 另外, foreach行的英文正确阅读。 For each item in $rssItems alias it as $rssItem . 对于$rssItems每个项目,别名为$rssItem Notice the difference between the plural and the singular. 注意复数和单数之间的区别。 The foreach runs its block for each item in $rssItems and for each iteration the variable $rssItem will contain the current value in $rssItems that the loop is on. foreach运行其块中的每个项目$rssItems和每个迭代变量$rssItem将包含在当前值$rssItems环路上。

Want more of a reason to use foreach ? 是否需要更多理由使用foreach If you need to work with the key too, foreach will give you both the key and value of every element of the hash (array). 如果您还需要使用键,foreach会为您同时提供哈希和每个哈希(数组)元素的值。

$words = array('hola' => 'hello', 'adios' => 'goodbye', 'gracias' => 'thank you');
foreach($words as $spanishWord => $englishTranslation) {
    echo $spanishWord . " in English is " . $englishTranslation . "\n";
}

Foreach also allows you with SPL to write classes that extend or implement an iterator. Foreach还允许您使用SPL编写扩展或实现迭代器的类。 Classes that contain collections, can function as a class but can be iterated over. 包含集合的类可以用作类,但可以对其进行迭代。 For example: 例如:

class PhotoAlbum implements IteratorAggregate {
    private $pictures = array();

    public function __construct($pictures) {
        $this->pictures = $pictures;
    }

    public function addPicture($picture) {
        $this->pictures[] = $picture;
    }

    public function share($friend) {
        // etc..
    }

    public function getIterator() {
        return new ArrayIterator($this->pictures);
    }
}

$album = new PhotoAlbum($picturesArrayFromDB);
foreach($album as $picture) {
    echo $picture;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM