PHP json_encode将行作为数组而不是对象返回

时间:2011-07-10 22:22:26

标签: php javascript arrays json

根据我的经验,当我从mysql表中json_encode数据时,输出是一个包含每一行作为对象的对象。我想要做的是将每一行作为一个数组,如下面的例子(不需要在那里的列名)。我怎么能这样做?

{ "Data": [
    ["1","Internet Explorer 4.0","Win 95+","4","X","1"],
    ["2","Internet Explorer 5.0","Win 95+","5","C","2"],
    ["3","Internet Explorer 5.5","Win 95+","5.5","A","3"],
    ["4","Internet Explorer 6","Win 98+","6","A","4"],
] }

2 个答案:

答案 0 :(得分:4)

使用mysql_fetch_row [docs]获取每一行。这将获得一行作为数值数组,并且这些也被编码为JSON数组:

$data = array();

while(($row = mysql_fetch_row($result))) {
    $data[] = $row;
}

echo json_encode(array('Data' => $data));

答案 1 :(得分:0)

未在口译员中检查: 您可以通过简单类型convertion更改变量类型:

$data = DB::get('SELECT * FROM `table` WHERE 1');
echo json_encode(array('Data' => (array)$data));

你也可以使用下一个函数:array mysql_fetch_array(resource $ result [,int $ result_type])