2016-05-06 28 views
1

我想合併兩個數組,但得到NULL。以下是我的代碼如何合併Codeigniter中的多個數組

$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']); 

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

回答

0

你要刪除的array_merge();

的第一個參數(NULL)什麼是$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']); 
+0

謝謝..它的工作.. –

0
$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']); 
0

你的代碼是完全正確的,唯一的問題是,你與$a = 1啓動計數器,並做$a++這將導致所以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']);