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

仅从几个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>';
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • donmqryh49993 2013-05-25 12:31

    Try with fetch_array like

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

    and dont use mysql_* functions due to it is depricated,instead you can use mysqli_* or pdo statements REFER THIS

    You can also use fetchAll();but i think it will used in PDO only

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题