我正在使用Codeigniter
来获取行。请仔细阅读以下代码。
//Model
public function selectData() {
$query = $this->db->query('SELECT * FROM tbl_favourites WHERE favourites_status = 1');
$count = $query->num_rows();
if($count > 0)
return $result = $query->result_array();
else
return 0;
}
//Controller
$all_favourites = $this->select->selectData();
if(!empty($all_favourites)) {
foreach($all_favourites as $favourites)
echo json_encode($favourites);
}
从上面的代码中,输出是
{"favourite_online_id":"3","favourite_online_url":"ddd","favourite_online_status":"0"}
{"favourite_online_id":"2","favourite_online_url":"http:\/\/www.google.com","favourite_online_status":"0"}
但我希望输出格式正确以满足android JSON。
所需的输出是,
[
{
"favourite_online_id": "3",
"favourite_online_url": "ddd",
"favourite_online_status": "0"
},
{
"favourite_online_id": "2",
"favourite_online_url": "http://www.google.com",
"favourite_online_status": "0"
}
]
答案 0 :(得分:1)
而不是使用
if(!empty($all_favourites)) {
foreach($all_favourites as $favourites)
echo json_encode($favourites);
}
直接使用
if(!empty($all_favourites)) {
echo json_encode($all_favourites );
}
答案 1 :(得分:1)
你可以双向进行
第一路
if(!empty($all_favourites)) {
echo json_encode($all_favourites);
}
第二路
如果你想在那个对象中添加一些内容,那么
$favouriteArray=[];
if(!empty($all_favourites)) {
foreach($all_favourites as $favourites){
array_push($favouriteArray, $favourites);
}
}
echo json_encode($favouriteArray);
答案 2 :(得分:1)
我认为你可以修改你的功能
public function selectData() {
$query = $this->db->query('SELECT * FROM tbl_favourites WHERE favourites_status = 1');
$count = $query->num_rows();
if($count > 0)
return $result = $query->result_array();
else
return array();
}
//Controller
$all_favourites = $this->select->selectData();
// if(!empty($all_favourites)) {
// foreach($all_favourites as $favourites)
// echo json_encode($favourites);
// }
echo json_encode($all_favourites);