阵列中的PHP JSON阵列
问题描述:
我有一个脚本循环并检索一些指定的值并将它们添加到php数组中。然后我把它的值返回给该脚本:阵列中的PHP JSON阵列
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
这是造成问题,当我尝试将数据解析到我的Android应用:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
这将返回的JSON值。结果需要是这样的:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
我意识到循环将数组添加到另一个数组中。我的问题是我如何循环php数组,并将所有这些值放入数组并将其输出为上面的JSON格式?
答
当然
我觉得$的GetList包含数组你的数据库中的列,
使用
$id_export[] = $getList[0]
也许可以做一些检查,以验证您的$的GetList阵列是有效的1大小
答
$db->getTest()
似乎是返回一个单个对象的数组,也许更多,然后您将添加到一个新的数组。请尝试以下方法之一:
如果将永远只能是一排,刚拿到0
指数(简单):
$id_export[] = $db->getTest($test['id'])[0];
或获取当前数组项:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
如果可能有不止一行,合并它们(无论是否更好和更安全的想法):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);