我有一个类属性,我定义了一个关联数组
private $jsonArray = array('Friends' => array());
我试图将数组中的每个朋友都放入数组中 [已接受] =测试
$query = "SELECT Username, Status
FROM Users
INNER JOIN Friends
ON Users.idUser = Friends.idFriend
WHERE Friends.idUser = ? ";
// Prepares and excutes the query
if($stmt = $this->connection->prepare($query))
{
$stmt->bind_param('s', $this->id);
$stmt->execute();
$stmt->bind_result($friend, $status);
for ($i=0; $stmt->fetch(); $i++)
{
$this->jsonArray['Friends'][$status] = $friend;
}
}
这是为其工作的朋友定义键的正确方法,但是当我json编码它的dict而不再是数组时
{
"response": {
"status":"Success",
"friends": [
"Andrew",
"Jake",
"Matt",
"Phil",
"Colton"
],
"groups": [
{
"GroupId": "12",
"GroupMembers": [
"Andrew",
"Matt",
"Colton"
],
"GroupName": “Group1”
},
{
"GroupId": "12",
"GroupMembers": [
"Phil",
"Matt",
"Colton"
],
"GroupName": "Room 201"
}
]
}
}
答案 0 :(得分:0)
有了这个,你每$friend
总会有一个[$status]
- 如果需要,那就没关系。但从外表来看,你会更喜欢这样的事情
for ($i=0; $stmt->fetch(); $i++) {
$this->jsonArray['Friends'][$status][] = $friend;
}
现在,$friend
内有[$status]
个数组。
...
Friends: {
"Accepted": ["friend1", "friend2", ...]
}
...
或者这个
for ($i=0; $stmt->fetch(); $i++) {
$this->jsonArray['Friends'][] = $friend;
}
既然你知道他们的$status
- 为什么要使用呢?
...
Friends: ["friend1", "friend2", ...]
...