$stmt = $db->prepare("SELECT * FROM friend JOIN user ON friend.uId=user.uId WHERE friend.friendId= ?");
$stmt->bind_param('s',$userId);
if($stmt->execute()){
$user = $stmt->get_result();
while ($obj = $user->fetch_object()) {
$friends[] = $obj;
}
echo json_encode($friends);
}
我上面的代码生成了一个数组
[{"uId":"2","firstName":"Gem","lastName":"Tang"},{"uId":"3","firstName":"James","lastName":"Lebron"}]
但我希望它可以是2个对象。
答案 0 :(得分:1)
你有一个长度为2的对象数组。使用JavaScript你可以像这样遍历它。
var o = [{"uId":"2","firstName":"Gem","lastName":"Tang"},{"uId":"3","firstName":"James","lastName":"Lebron"}];
for(var i = 0; i < o.length; i++) {
var row = o[i];
console.log(row.firstName);
}
答案 1 :(得分:-1)
:
您可以使用foreach:
$object = new stdClass();
foreach ($obj as $key => $value)
{
$object->$key = $value;
}
$friends[$obj['uId']] = $object;
或通过json函数:
$friends[$obj['uId']] = json_decode(json_encode($obj), FALSE);