简体   繁体   中英

How do I insert a multidimensional array into another array in a loop?

I have this code:

$postList = array();

foreach($post as $blue)
{
    $text = $string;
    $url = trim(url);

    $newPost = array(  "ID" => $counter,
                        "Text" => $text,
                        "url" => $url );
    $postList = array_merge($postList, $newPost);
    $counter += 1;
}

This code does not work and what I find into the postList array is the last post item, not the list. How do I insert all the items into the array?

Thanks in advance

try this

$postList = array();
$counter = 0;
foreach($post as $blue)
{
    $text = $string;
    $url = trim(url);

    $newPost = array(  "ID" => $counter,
                        "Text" => $text,
                        "url" => $url);
    $postList[] =  $newPost;
    $counter += 1;
}

Save creating an extra variable try:

$postList = array();

foreach($post as $blue)
{
    $text = $string;
    $url = trim(url);

    $postList[] = array(  "ID" => $counter,
                        "Text" => $text,
                        "url" => $url );
    $counter += 1;
}

In Object Oriented programming languages there is push method in the Array object. So it's something like this.

array.push(element);

This means push element at the end of the array. In PHP there is also push method, but it's static function, PHP libraries are like that. So you do something like this:

$persons = Array();
$person = Array('id' => 1, 'name' => 'my name');
array_push($persons, $person);

or

$array[] = $element;

The first one is more explicit and you'll understand better what it does. You should read more about data structures in PHP.

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