如何在循环中将多维数组插入到另一个数组中?


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

我有这样的代码:

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

这段代码不起作用,我在postList数组中找到的是最后一个post条目,而不是列表。如何将所有项插入数组?

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;
}

保存创建额外的变量try:

$postList = array();
foreach($post as $blue)
{
    $text = $string;
    $url = trim(url);
    $postList[] = array(  "ID" => $counter,
                        "Text" => $text,
                        "url" => $url );
    $counter += 1;
}

在面向对象编程语言中,Array对象中有push方法。就像这样

array.push(element);

表示将元素推到数组的末尾。PHP中也有push方法,但它是静态函数,PHP库就是这样。你可以这样做:

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

$array[] = $element;

第一个更明确,您将更好地理解它的作用。你应该阅读更多关于PHP数据结构的知识