我不知道为什么当我回显json_encode一个查询结果集时,我得到每个对象之前的结果行的编号。我只想计算返回的总行数,并在JSON字符串的开头只显示一次,然后只返回行。即使用以下代码:
//...active record query
$result = $this->db->get();
$data = array();
$count = 1;
foreach($result->result() as $row)
{
$data['count'] = $count;
$entry = array();
$entry['firstname'] = $row->first_name;
$entry['lastname'] = $row->last_name;
$entry['jobtitle'] = $row->title;
$entry['dept'] = $row->dept_name;
$entry['deptid'] = $row->dept_no;
if($row->emp_no == null)
{
$entry['ismanager'] = 0;
}
else
{
$entry['ismanager'] = 1;
}
$data[] = $entry;
$count++;
}
return $data;
然后json_encode它在控制器中,我得到:
{"count":35,"0":{"firstname":"Georgi","lastname":"Facello","jobtitle":"Senior Engineer","dept":"Development","deptid":"d005","ismanager":0},"1":{"firstname":"Kirk","lastname":"Facello","jobtitle":"Senior Engineer","dept":"Development","deptid":"d005","ismanager":0},....rest of the query results
在行结果之前,我不想要的是"0"
和"1"
等。我已经有了返回结果的总数,所以我不需要单独的行号。
如果有人能帮助我,我会很感激,谢谢。
答案 0 :(得分:1)
如果您尝试将数组序列化为JSON,它将变为如下所示:
[elem1, elem2, elem3, ...]
但是如果那个“数组”有其他字段,那么它将被序列化为一个对象:
{"field":value, "0":elem1, "1":elem2, "2":elem3, ...}
由于无法使用数组语法序列化field
,并且json_encode
不能简单地丢弃它,因此它使用对象语法。如the docs中所述:
注意:强>
对数组进行编码时,如果键不是从0开始的连续数字序列,则所有键都编码为字符串,并为每个键值对明确指定。
可能的解决方法是将计数与元素列表分开:
$data = array();
$list = array();
$data['list'] = list;
$count = 1;
foreach($result->result() as $row)
{
$data['count'] = $count;
$entry = array();
...
$list[] = $entry;
$count++;
}
这将序列化为:
{"count":35,"list":[{"firstname":"Georgi","lastname":"Facello","jobtitle":"Senior Engineer","dept":"Development","deptid":"d005","ismanager":0},{"firstname":"Kirk","lastname":"Facello","jobtitle":"Senior Engineer","dept":"Development","deptid":"d005","ismanager":0},....rest of the query results]}
答案 1 :(得分:0)
看起来您可能在JSON_FORCE_OBJECT
上使用json_encode
,这将始终使您的数字索引显示为属性。您应该在问题中显示json_encode
步骤。
如果关闭选项并使用默认编码,则仍需要将数字索引数组嵌套在其自己的属性中,否则数字索引将显示为属性以生成有效的JSON。也许在将行分配给对象时可能会执行以下操作:
$data['records'][] = $entry;