dpqmu84646 2013-05-25 12:29
浏览 84
已采纳

仅从几个Mysql字段创建一个json数组,同时输出其他的[重复]

This question already has an answer here:

I need to create a json array from only the id and name fields below, while outputting the others. How can I best achieve this? I'm trying to get the output like this:

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"}

I'll use the json array for something else later in a different form. The array keys have to remain the same and cannot be changed.

The output script is pretty simple like this.

    $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'];

    }

I'm currently doing like this, but do you see a better way to do it?

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>';
    }

There are many more fields that'll go into the array. I've used only a few for this example.

</div>
  • 写回答

2条回答 默认 最新

  • dongpeixiong5943 2013-05-25 12:40
    关注

    For the sake of having less lines and a save the use of a variable you can do it like this:

    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>';
        }
    

    Another way, wold be to print your values with a foreach. About the Json, well, the same as before...

    while( $row = $stmt->fetch() ) {
        foreach ($row as $value)
        {
            echo $value.' ';
        }
    
        echo json_encode(array('userId' => $row['id'], 'userName' => $row['name']));
        echo '<br>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大