简体   繁体   中英

PHP: Insert array into an array

Im trying to create a single array with 100 items. First for-loop runs 10 times, and for each run it runs another for-loop who inserts 10 items into the array.

But the result is only the last 10 items:

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>";
}
$feeds[] = feed($x);

You're re-assigning $feeds not inserting in to it.

BTW, you should declare $feeds before you use it:

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

And, as a re-write that, you actually iterate 11 times ( $x <= 10 ). I think you just want $x < 10 (given you start at a 0 index).


Working Code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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