我在PHP中创建JSON以从另一个应用程序读取,我想将JSON数据分类为
jobs:
job:
ID: 123
name: Job Name 1
job:
ID: 321
name: Job Name 2
job:
ID: 231
name: Job Name 3
我得到的是
0:
ID: 123
name: Job Name 1
1:
ID: 321
name: Job Name 2
2:
ID: 231
name: Job Name 3
我用来创建JSON的PHP代码如下:
$rs = mysqli_query($dbc, "SELECT id, name FROM job");
while($obj = mysqli_fetch_object($rs)) {
$arr[] = $obj;
}
echo json_encode($arr, JSON_FORCE_OBJECT);
如何将JSON中的每个项目归类为“作业”并将整个列表归类为“作业”,我需要做什么?
答案 0 :(得分:0)
试试这个
$rs = mysqli_query($dbc, "SELECT id, name FROM job");
while($obj = mysqli_fetch_object($rs)) {
$arr['job'][] = $obj;
}
echo json_encode($arr, JSON_FORCE_OBJECT);
答案 1 :(得分:0)
试试这样的
while($obj = mysqli_fetch_object($rs)) {
$arr['jobs'][]['job'] = $obj;
}
echo json_encode($arr);
更新:
$obj_user1 = new stdClass;
$obj_user1->id = "1";
$obj_user1->name = "a";
$obj_user2 = new stdClass;
$obj_user2->id = "2";
$obj_user2->name = "b";
$obj_user = array($obj_user1,$obj_user2);
foreach($obj_user as $a){
$arr['jobs'][]['job'] = $a;
}
print_r(json_encode($arr));
输出
{"jobs":[{"job":{"id":"1","name":"a"}},{"job":{"id":"2","name":"b"}}]}