1

我不知道为什么当我回显 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",在行结果之前。我已经有了返回结果的总数,所以我不需要单独的行号。

如果有人可以帮助我,我将不胜感激,谢谢。

4

2 回答 2

1

如果您尝试将数组序列化为 JSON,它将变成这样:

[elem1, elem2, elem3, ...]

但是如果那个“数组”有其他字段,那么它将被序列化为一个对象:

{"field":value, "0":elem1, "1":elem2, "2":elem3, ...}

由于没有办法field使用数组语法进行序列化,json_encode也不能简单地丢弃它,所以它使用对象语法。如文档中所述

笔记:

在对数组进行编码时,如果键不是从 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]}
于 2012-12-19T21:43:34.613 回答
0

看起来您可能正在使用它JSON_FORCE_OBJECTjson_encode这将始终使您的数字索引显示为属性。你应该json_encode在你的问题中展示你的步骤。

如果您关闭选项并使用默认编码,您仍需要将数字索引数组嵌套在其自己的属性中,否则数字索引将显示为属性以生成有效的 JSON。因为在将行分配给对象时可能会做这样的事情:

$data['records'][] = $entry;
于 2012-12-19T21:44:16.283 回答