将查询结果转换为关联数组 [英] Turning a query result to an associative array

查看:77
本文介绍了将查询结果转换为关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的PHP中,我正在运行一个简单的查询,该查询从我拥有的数据库中返回一个结果集(0个或多个)。

In my php I am running a simple query which returns a resultset(0 or many) from the database I have.

当前在前面,结果看起来像这:

Currently on the fronted the rersult looks like this :

name: Smoothie description: Banana Smothie name: Phad Thai description: Noodles with shrimps name: Noodles description: Noodles with noodles.

字符串也可以看起来像这样,又名名称:冰沙描述:香蕉Smothie 或包含更多条目,如上面的示例。

The string can also look like this, aka name: Smoothie description: Banana Smothie or with more entries, like in the example above.

我的目标是从结果中得到一个关联数组,我可以将其转换为json字符串,并将其传递给前端。

What I am aiming to have is an associative array from my result, which I can turn into json string and pass it to the frontend.

不幸的是,到目前为止,我一直没有尝试过。

Unfortunately what i tried so far didn't work.

这是我的php:

<?php
include_once 'db/dbconnect.php';
$input = json_decode(stripcslashes($_POST['data']));

for ($i=0; $i < count($input); $i++) {
  $stmt=$con->prepare("SELECT recipes.recipeName, recipes.recipeDescription FROM ingredients, recipes, recipesingredients WHERE recipes.recipeId = recipesingredients.recipeIdFK AND recipesingredients.ingredientIdFK = ingredients.IngredientId AND ingredients.ingredientName = ?");
  $stmt->bind_param("s", $input[$i]);
  $stmt->execute();
  $stmt->store_result();
  $stmt->bind_result($db_recipe_name, $db_recipe_description);

  while ($stmt->fetch()) {
    echo "name: ".$db_recipe_name." description: ".$db_recipe_description." ";
  }
}



 ?>

有人可以帮助我将查询的结果转换为具有当前代码的关联数组吗?

Can someone help me make the result from the query to an associative array with the current code i have?

推荐答案

只需将每个数组添加到一个数组中。另外,请使用现代的JOIN语法:

Just add each one to an array. Also, use modern JOIN syntax:

<?php
include_once 'db/dbconnect.php';
$input = json_decode(stripcslashes($_POST['data']));

for ($i=0; $i < count($input); $i++) {
    $stmt=$con->prepare("SELECT recipes.recipeName, 
        recipes.recipeDescription 
        FROM ingredients i
        JOIN recipesingredients ri
            ON ri.ingredientIdFK = i.IngredientId
        JOIN recipes r
            ON r.recipeId = ri.recipeIdFK
        WHERE i.ingredientName = ?");
    $stmt->bind_param("s", $input[$i]);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($db_recipe_name, $db_recipe_description);

    $rslt = array();
    $rowno = 0;
    while ($stmt->fetch()) {
        $rslt[$rowno] = array('name' => $db_recipe_name, 'description' => $db_recipe_description);
        $rowno++;
        echo "name: ".$db_recipe_name." description: ".$db_recipe_description." ";
    }
    $jsonRslt = json_encode($rslt);
    echo "<p>JSON Results:<pre>".$jsonRslt."</pre></p>\n";
    $stmt->close();
}

这篇关于将查询结果转换为关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆