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条)

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题