2016-05-04 147 views
0

我的代碼生成陣列的動態

$records = array(); 
$records["data"] = array(); 
    foreach ($rows as $row) {//select from DB 
     $records["data"][] =array();//XXXX 
       foreach($this->t_data['columns'] as $column) {//columns for table 
        $records['data'][][]=$row[$column['name']];//THIS need to add into XXXX array 
       } 
    } 
$records["draw"] = $sEcho; 
return json_encode($records); 

這部分在嘗試以多種方式將數據添加到陣列。此代碼來自數據表。

這wotking代碼,靜態

foreach ($tickete as $row) { 
    $records["data"][] = array(
     '<input type="checkbox" name="idticket" value="' . $row['id'] . '">', 
     $row['name'], 
     $row['type'], 
     $row['state'] 
    ); 
} 

格式:

{"data":[ 
["ID1","Name","Type","State"], 
["ID2","Name","Type","State"], 
["ID3","Name","Type","State"], 
["ID4","Name","Type","State"], 
["ID5","Name","Type","State"]],"draw":2,"recordsTotal":50,"recordsFiltered":50} 
+0

你想要的陣列格式? –

+0

我編輯問題 –

回答

0

多解:

1)臨時陣列,推底:

foreach ($rows as $row) { 
    $subArray = array(); 
    foreach($this->t_data['columns'] as $column) { 
     $subArray[] = $row[$column['name']]; 
    } 
    $records["data"][] = $subArray; 
} 

2)使用數組ind例如:

foreach ($rows as $row) { 
    $records["data"][] = array(); 
    foreach($this->t_data['columns'] as $column) { 
     $records["data"][count($records["data"]) - 1][] = $row[$column['name']]; 
    } 
} 

3)參考使用指數(有用的新創建的數組只有當你需要更頻繁地訪問):

foreach ($rows as $row) { 
    $records["data"][] = array(); 
    $subArray = &$records["data"][count($records["data"] - 1)]; 
    foreach($this->t_data['columns'] as $column) { 
     $subArray[] = $row[$column['name']]; 
    } 
} 
+0

謝謝,選項1正在完美工作 –