在CodeIgniter中格式化多维数组

时间:2011-03-04 23:52:02

标签: php arrays codeigniter multidimensional-array

我试图从CI查询和后续的JSON_encode中获取以下输出格式:

{"clients":{"id":"3","name":"Client Number1"},{"id":"2","name":"Client Number2"},{"id":"1","name":"Test Client"},{"id":"4","name":"Test Client2"}}

结合控制器和模型中的小函数,我正在使用:

$query = $this->db->query('SELECT id, name FROM clients ORDER BY name ASC');
        foreach ($query->result() as $row)
        {
            $arr['clients'][] = $row;
        }

        $json = json_encode($arr, JSON_FORCE_OBJECT);
        echo $json;

此代码输出(如下),其中包括数组索引值(“1”,“2”......等)如何从结果中删除这些索引值?感谢您提供的任何帮助。这不是一个破坏性的危机。我可以在交易的另一边解析它们......但是认为无所不知的SO可能知道如何更优雅地做到这一点!!

{"clients":{"0":{"id":"3","name":"Client Number1"},"1":{"id":"2","name":"Client Number2"},"2":{"id":"1","name":"Test Client"},"3":{"id":"4","name":"Test Client2"}}}

2 个答案:

答案 0 :(得分:2)

编辑:我错了。

显然,PHP的json_encode中的所有对象都作为关联数组打印,因此它始终打印键。至少,这是我从PHP手册中的json_encode页面获得的氛围。

删除JSON_FORCE_OBJECT(并使用$query->result_array())删除了键,但不是完全您正在寻找的内容:

{"clients":[{"id":"3","name":"Client Number1"},{"id":"2","name":"Client Number2"},{"id":"1","name":"Test Client"},{"id":"4","name":"Test Client2"}]}

答案 1 :(得分:1)

谢谢Trevor ......我很感激帮助。你实际上指出了我正确的方向。我忘记了'JSON_FORCE_OBJECT'参数可能会搞乱。事实上它是......见下文:

$query = $this->db->query('SELECT id, name FROM clients ORDER BY name ASC');
        foreach ($query->result() as $row)
        {
            $arr['clients'][] = $row;
        }

        $json = json_encode($arr); // Note JSON_FORCE_OBJECT removed
        echo $json;

此代码输出:

{"clients":[{"id":"3","name":"Client Number1"},{"id":"2","name":"Client Number2"},{"id":"1","name":"Test Client"},{"id":"4","name":"Test Client2"}]}

我认为只是允许一个JSONArray(因此是方括号)存在于JSONObject中......我可以忍受它。

再次感谢特雷弗!