获取多个分离的对象。

时间:2014-04-25 08:38:33

标签: php database mysqli

$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个对象。

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)

在while循环中

您可以使用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);