我想構建一個包含內部對象的json對象。爲什麼我無法格式化我的JSON對象?
我想下面的代碼 - 在$ids
是包含一些ID的數組:
$result = array();
foreach ($ids as $value) {
$tempArray = getCustomOptions($host, $dbUsername, $dbPassword, $dbName, $_SESSION['companyId'], $value);
array_push($result, $tempArray);
}
print_r(json_encode($result));
的getCustomOptions()
還使用下面的腳本返回數組:
$dataArray = [];
while ($stmt->fetch()) {
$dataArray[] = array(
'id' => $id,
'description' => $description
);
}
的問題是,當我print_r(json_encode($result));
我收到以下結果:
[
[
{
"id":21,
"description":"Bshd"
},
{
"id":22,
"description":"Gandhi "
},
{
"id":23,
"description":"aaaa"
},
{
"id":24,
"description":"bbbbb"
}
],
[
{
"id":12,
"description":"121"
},
{
"id":13,
"description":"qwe"
},
{
"id":16,
"description":"wD2"
},
{
"id":17,
"description":"we"
}
],
[
]
]
正如你可以看到它返回一個數組裏面某些陣列,但我真正需要的是以下結構:
{
"data1":[
{
"id":21,
"description":"Bshd"
},
{
"id":22,
"description":"Gandhi "
},
{
"id":23,
"description":"aaaa"
},
{
"id":24,
"description":"bbbbb"
}
],
"data2":[
{
"id":12,
"description":"121"
},
{
"id":13,
"description":"qwe"
},
{
"id":16,
"description":"wD2"
},
{
"id":17,
"description":"we"
}
]
}
我知道我失去了一些東西真的很小,基本在這裏,但對我來說,在PHP中的JSON操作仍然很難。
有人可以給我一個線索或推?
這正是我一直在尋找的!非常感謝! – Slim