插入元素PDO结果数组

时间:2017-03-01 11:08:25

标签: php arrays pdo

这是我的代码:



$stmt = $db->prepare("SELECT * FROM wishlists WHERE user_id='1'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$res = array('saved_id' => "1");
array_push($result, $res);
echo json_encode($result);




最终结果:

[{"id":"1","user_id":"1","name":"San Francisco","privacy":"0","pick":"Yes"},{"saved_id":"1"}]

但我想在第一个数组中显示saved saved_id,例如:

[{"id":"1","user_id":"1","name":"San Francisco","privacy":"0","pick":"Yes","saved_id":"1"}]
你能帮帮我吗?

2 个答案:

答案 0 :(得分:3)

如果预期会有多个结果,最好在查询中正确注入

$saved_id = 1;
$user_id = 1;
$stmt = $db->prepare("SELECT *, ? as saved_id FROM wishlists WHERE user_id=?");
$stmt->execute([$saved_id, $user_id]);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);

但如果只需要一行,则必须使用fetch()而不是fetchAll();
然后你可以添加你想要的任何元素:

$stmt = $db->prepare("SELECT * FROM wishlists WHERE user_id='1'");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$result['saved_id'] = "1";
echo json_encode($result);

答案 1 :(得分:1)

更改

array_push($result, $res);

$result = array_map( function($r) use($res){
    return array_merge($r, $res);
}, $result);