dongnaoxia0927
2014-08-06 09:12
浏览 375
已采纳

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

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

图片转代码服务由CSDN问答提供 功能建议

我有这段代码:

  $ 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数组中找到的是最后一个帖子项,而不是列表。 如何将所有项插入到 数组?

提前致谢

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douchuitang0642 2014-08-06 09:14
    已采纳

    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;
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dsplos5731 2014-08-06 09:20

    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;
    }
    
    评论
    解决 无用
    打赏 举报
  • duanchu0031 2014-08-06 09:21

    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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题