$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);