PHP:将数组插入数组中

时间:2013-09-06 16:10:40

标签: php arrays for-loop

我试图创建一个包含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>";
}

1 个答案:

答案 0 :(得分: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);