您如何追加到PDO结果集数组或Json_encoded字符串? [英] How do you append to a PDO resultset array or Json_encoded string?
问题描述
我想先将更多信息添加到json对象,然后再将其发送回我的应用.
I want to add a bit more information to a json object before sending it back to my app.
$sql = "SELECT * FROM users WHERE repo=?";
$q=$dbh->prepare($sql);
$q->execute(array($repo));
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res['isnew']="1"; //this part isn't working
echo '{"items":'. json_encode($res) .'}';
当我回显($ res)时,PDO查询返回这样的结果集
The PDO query returns a result set like this when I echo($res)
Array{"items":[{"uid":"10","repo":"bnef"}]}
然后将其编码回jquery- echo'{"items":'. json_encode($ res).'}'; 给我
then it gets encoded back to jquery- echo '{"items":'. json_encode($res) .'}'; giving me
{"items":[{"uid":"10","repo":"bnef}]}
我想在其中添加"isnew":"1",但是当我尝试时 $ res ['isnew'] ="1";或我最终遇到的array_merge
I'd like to add "isnew":"1" to that but when I try $res['isnew']="1"; or array_merge I end up with
{"items":{"0":{"uid":"10","repo":"bnef"},"isnew":"1"}}
不起作用.我需要
{"items":[{"uid":"10","repo":"bnef, "isnew":"1"}]}
我会误导这样做吗?
推荐答案
我误解了您的问题,并对代码感到困惑...您应该使incat最初与数组不对齐,请尝试以下操作:
I misread your question and got confused on the code... you shoudl incat be dealign with an array initially try the following:
$sql = "SELECT * FROM users WHERE repo=?";
$q=$dbh->prepare($sql);
$q->execute(array($repo));
$items = $q->fetchAll(PDO::FETCH_OBJ);
// you actually wnt isnew as a property of each row
// so you need to loop over the results
foreach($items as $key => $item){
$item->isnew = 1;
}
echo json_encode(array(
'items' => $items
));
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res['isnew']="1"; //this part isn't working
它不起作用,因为您使用的是FETCH_OBJ
而不是FETCH_ASSOC
,所以您使用StdObject
实例而不是数组来工作.在这种情况下,您需要使用->
进行分配:
Its not working because you used FETCH_OBJ
instead of FETCH_ASSOC
so youre wokring with an StdObject
instance not an array. In that case you need to use ->
to assign:
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res->isnew = "1";
或者,您也可以将其作为关联数组来获取:
Alternatively you could fetch as an associative array:
$res = $q->fetchAll(PDO::FETCH_ASSOC);
$res['isnew']="1"; //this will work now
Additionalyl我不会尝试操作JSON序列化的字符串.我会本地做所有修改:
Additionalyl i wouldnt try to manipulate the JSON serialized string. I would doo all modifications natively:
$items = array(
'items' => $res
);
echo json_encode($items);
这篇关于您如何追加到PDO结果集数组或Json_encoded字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!