簡體   English   中英

如何在Codeigniter中合並多個數組

[英]How to merge multiple arrays in Codeigniter

我試圖合並兩個數組,但得到NULL 以下是我的代碼

$a = 1;
foreach($codes as $values) {
$id = $values['id'];
$post_data = array ( 
    "id" => $id,
    "name" => $this->input->post('Name'),
    "from_date" => $this->input->post('FromDate'),
    "to_date" => $this->input->post('ToDate')
    );
    $this->data['output' . $a++] = $this->my_modal->simple_post($post_data);
}

$this->data['output'] = array_merge($this->data['output1'], $this->data['output2']);

var_dump($this->data['output']);

任何建議將不勝感激。 謝謝..

你必須刪除array_merge();的第一個參數( NULL array_merge();

什么是$this->input->$id 你的意思是$id嗎?

在這種環境中,最好使用array_push();

$a = 1;
$this->data['output'] = array();
foreach($codes as $values)
{
    $id = $values['id'];
    $post_data = array ( 
    "id" => $id,
    "name" => $this->input->post('Name'),
    "from_date" => $this->input->post('FromDate'),
    "to_date" => $this->input->post('ToDate')
    );

    $new_data = $this->my_modal->simple_post($post_data);
    array_push($this->data['output'], $new_data);
}

var_dump($this->data['output']);
 $a = 1;
 $this->data['output'] = array();
 foreach($codes as $values){
$id = $values['id'];
$post_data = array ( 
"id" => $id,
"name" => $this->input->post('Name'),
"from_date" => $this->input->post('FromDate'),
"to_date" => $this->input->post('ToDate')
);

$data['output2']= $this->my_modal->simple_post($post_data);
if(count($this->data['output1']) > 1)   {
        $this->data['all']      =   array_merge($this->data['output1'],$data['output2']);
    }else {
        $this->data['all']      =   $data['output1'];
    }
 }
 print_r($this->data['all']);

你的代碼是完全正確的,唯一的問題是你用$a = 1啟動計數器,並且執行$a++將導致2.因此output1不存在。 但是如果你寫(注意微妙的變化):

$a = 1;
foreach($codes as $values) {
    $id = $values['id'];
    $post_data = array ( 
        "id" => $id,
        "name" => $this->input->post('Name'),
        "from_date" => $this->input->post('FromDate'),
        "to_date" => $this->input->post('ToDate')
    );
    $this->data['output' . $a] = $this->my_modal->simple_post($post_data); // $a = 1 now
    $a++; // $a becomes 2 here
}

$this->data['output'] = array_merge($this->data['output1'], $this->data['output2']);

var_dump($this->data['output']);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM