注意:本机查询原则的数组结果中未定义索引

Notice: Undefined index in array result of native query doctrine

我在 Doctrine 中获得了本机查询的数组结果。查询是

    $conn = $em->getConnection();
    $sql = 'SELECT * FROM Stock_drink d WHERE id=?';
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(1,$idstockdrink);
    $stmt->execute();
    $stockdrink = $stmt->fetchAll();

$stockdrink 内容是

"{"stockdrink":[{"id":"39","name":"limon","stockamount":"14","price":"2.20","Drink_id":"5","Bar_id":"12"}]}"

现在我想用这些句子获取 $stockdrink 数组的一些值,但总是得到未定义索引的通知。我正在查看文档,但还没有看到解决方案。

    $iddrink = $stockdrink["name"];
    $name = $stockdrink["name"];
    $price = $stockdrink["price"];

提前致谢!!!

因为 fetchAll() 方法 "fetches all results into an array",所以在您的特定情况下,您必须这样修改代码:

$conn = $em->getConnection();
$sql = 'SELECT * FROM Stock_drink d WHERE id=?';
$stmt = $conn->prepare($sql);
$stmt->bindValue(1,$idstockdrink);
$stmt->execute();

$stockdrinks = $stmt->fetchAll();

$stockdrink = $stockdrinks[0];

$iddrink = $stockdrink["name"];
$name = $stockdrink["name"];
$price = $stockdrink["price"];

更多信息请点击此处http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html#fetchall