【问题标题】:Problem storing prepared statement result into json array将准备好的语句结果存储到 json 数组中的问题
【发布时间】:2019-06-17 23:32:20
【问题描述】:

我想将准备好的语句的结果存储到一个数组中,然后转换成一个 json。但我没有得到我想要的 json 格式。

 $stmt = $conn->prepare("select course_id,course_name from mas_course");
$stmt->execute();

$stmt->store_result();
$stmt->bind_result($courseid, $coursename); 
$cnt = $stmt->num_rows;

$myObj = array();

 while ($stmt->fetch()) {
        $myObj['courseid'][] = $courseid;
        $myObj['coursename'][] = $coursename;
    }

$myJSON = json_encode($myObj);
    echo $myJSON;

它给了我像

这样的输出
{
"id": ["123", "345"],
"name": ["abc", "xyz"]
}

但我想要

[{
    "id": "123",
    "name": "abc"
},
{
    "id": "345",
    "name": "xyz"
}]

【问题讨论】:

    标签: php json multidimensional-array associative-array


    【解决方案1】:

    要以所需格式获取 json,数据库中的每一行都需要是输出 json 中的一个条目 - 创建一个数组并在循环中添加到它

    $output=[];
    while( $stmt->fetch() ) $output[]=(object)array(
        'id'    =>  $courseid,
        'name'  =>  $coursename
    );
    $json=json_encode( $output );
    

    【讨论】:

    • 谢谢 :) 我在考虑 foreach 循环,但我认为它不会在这里工作,或者工作?
    【解决方案2】:

    您以错误的顺序添加到结果中,但由于您只获取您想要的列,您可以缩短它以使用 fetch_all(),这将获取所有数据而无需循环...

    $output = $stmt->fetch_all(MYSQLI_ASSOC);
    $json=json_encode( $output );
    

    如果您希望数组中的列具有不同的名称,请在 SQL 中使用别名来设置名称。

    【讨论】:

    • 又短又甜!
    猜你喜欢
    • 2014-02-14
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 2011-07-13
    • 2014-06-30
    • 1970-01-01
    相关资源
    最近更新 更多