1

我试图创建一个包含 100 个项目的单个数组。第一个 for 循环运行 10 次,每次运行它都会运行另一个 for 循环,该循环将 10 个项目插入到数组中。

但结果只有最后 10 项:

class Feed {

public $url;
public $title;

}

function feeds_array() {

for ($x = 0; $x <= 10; $x++) {
    $feeds = feed($x);
}
return $feeds;
}

function feed($x) {
for ($i = 1; $i <= 10; $i++) {
    $feed = new Feed();
    $feed->url = "u" . $x;
    $feed->title = "t" . $i;
    $feeds[] = $feed;
}
return $feeds;
}


$feeds = feeds_array();

foreach ($feeds as $feed) {
echo 'This feed is a ' . $feed->url . ' ' . $feed->title;
echo "<br>";
}
4

1 回答 1

2
$feeds[] = feed($x);

您正在重新分配$feeds不插入它。

顺便说一句,您应该$feeds在使用之前声明:

function feeds_array(){
  $feeds = array();
  for ($x = 0; $x < 10; $x++){
    $feeds[] = feed($x);
  }
  return $feeds;
}

而且,作为重写,您实际上迭代了 11 次 ( $x <= 10)。我想你只是想要$x < 10(假设你从 0 索引开始)。


工作代码:

// original feed object
class Feed
{
    public $url;
    public $title;
}

// root method to create an array of arrays
function feeds_array(){
    // create a variable we're going to be assigning to
    $feeds = array();
    // iterate ten times
    for ($x = 0; $x < 10; $x++){
            // merge/combine the array we're generating with feed() in to
            // our current `$feed` array.
        $feeds = array_merge($feeds, feed($x));
    }
    // return result
    return $feeds;
}

// nested function to create and return an array
function feed($x){
    // again, initialize our resulting variable
    $feeds = array();
    // iterate over it 10 times
    for ($y = 0; $y < 10; $y++){
            // create the new object
        $feed = new Feed();
        $feed->url = 'u' . $x;
        $feed->title = 't' . $y;
            // push it in to the result
        $feeds[] = $feed;
    }
    // return the result
    return $feeds;
}

// entry point
$feeds = feeds_array();
var_dump($feeds);
于 2013-09-06T16:12:07.913 回答