我有这部分代码
$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)
多种解决方案:
1)最后推送的临时数组:
foreach ($rows as $row) {
$subArray = array();
foreach($this->t_data['columns'] as $column) {
$subArray[] = $row[$column['name']];
}
$records["data"][] = $subArray;
}
2)使用数组索引:
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']];
}
}