[英]How do you append to a PDO resultset array or Json_encoded string?
我想先将更多信息添加到json对象,然后再将其发送回我的应用。
$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) .'}';
当我echo($ res)时,PDO查询返回这样的结果集
Array{"items":[{"uid":"10","repo":"bnef"}]}
然后将其编码回jquery- echo'{“ items”:'。 json_encode($ res)。'}'; 给我
{"items":[{"uid":"10","repo":"bnef}]}
我想在其中添加“ isnew”:“ 1”,但是当我尝试$ res ['isnew'] =“ 1”;时, 或我最终得到的array_merge
{"items":{"0":{"uid":"10","repo":"bnef"},"isnew":"1"}}
这不起作用。 我需要
{"items":[{"uid":"10","repo":"bnef, "isnew":"1"}]}
我在尝试这样做时会误导吗?
我误解了您的问题,并对代码感到困惑...您应该将incat与数组反对齐,首先尝试以下操作:
$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
实例而不是数组StdObject
了。 在这种情况下,您需要使用->
来分配:
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res->isnew = "1";
或者,您可以获取为关联数组:
$res = $q->fetchAll(PDO::FETCH_ASSOC);
$res['isnew']="1"; //this will work now
我不会尝试操纵JSON序列化字符串。 我会本地做所有修改:
$items = array(
'items' => $res
);
echo json_encode($items);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.