仅从几个Mysql字段创建json数组,同时输出其他字段


Create a json array from only a few Mysql fields while outputting the others

我需要从下面的idname字段创建一个json数组,同时输出其他字段。我怎样才能最好地做到这一点?我试图得到这样的输出:

Peter    30     1 Elm Street 91550  {"userId":"1","userName":"Peter"}
James    31     2 Elm Street 91551  {"userId":"2","userName":"James"}
John     32     3 Elm Street 91552  {"userId":"3","userName":"John"}
Andrew   34     4 Elm Street 91553  {"userId":"4","userName":"Andrew"}

我将在后面以不同的形式使用json数组。数组键必须保持不变,不能更改。

输出脚本非常简单,如下所示:

    $stmt = $conn->prepare("select id, name, age, address, pincode from json");
    $stmt->execute();
    while( $row = $stmt->fetch() ) {
        echo $row['name']." ".$row['age']." ".$row['address']." ".$row['pincode'];
    }

我现在就是这样做的,但是你有更好的方法吗?

while( $row = $stmt->fetch() ) {
        echo $row['name']." ".$row['age']." ".$row['address']." ".$row['pincode'];
        $myarray['userId'] = $row['id'];
        $myarray['userName'] = $row['name'];
        echo json_encode($myarray);
        echo '<br>';
    }

数组中还有更多的字段。在这个例子中我只使用了几个

为了减少行数和节省变量的使用,您可以这样做:

while( $row = $stmt->fetch() ) {
        echo $row['name']." ".$row['age']." ".$row['address']." ".$row['pincode'];
        echo json_encode(array('userId' => $row['id'], 'userName' => $row['name']));
        echo '<br>';
    }
另一种方法是用foreach来打印你的值。关于Json,好吧,和以前一样…
while( $row = $stmt->fetch() ) {
    foreach ($row as $value)
    {
        echo $value.' ';
    }
    echo json_encode(array('userId' => $row['id'], 'userName' => $row['name']));
    echo '<br>';
}

Try with fetch_array like

$result = $stmt->fetch_array();
json_encode($result);

和不要使用mysql_*函数,因为它是被弃用的,你可以使用mysqli_*或pdo语句 reference THIS

你也可以使用fetchAll();但我认为它将只用于PDO