调整数组和对象中的json响应

时间:2016-08-02 05:22:20

标签: mysql json web-services

我正在处理Web服务和json响应。

我收到了API的回复:

[  
    [  
        {  
            "id":"1",
            "unique_id":"579992ffd1",
            "contact_name":"qweryyy",
            "user_phone_number":"03331524145",
            "created_at":"2016-08-01 15:53:59"
        },
        {  
            "id":"2",
            "unique_id":"579992ffd1",
            "contact_name":"qwer",
            "user_phone_number":"03331524231",
            "created_at":"2016-08-01 16:04:59"
        },
        {  
            "id":"3",
            "unique_id":"579992ffd1",
            "contact_name":"qwer",
            "user_phone_number":"0333152111",
            "created_at":"2016-08-01 16:05:08"
        }
    ]
]

但我需要像JSON一样显示响应:

{  
    "unique_id":"579992ffd1",
    "user":[  
        {  
            "id":"1",
            "contact_name":"qweryyy",
            "user_phone_number":"03331524145",
            "created_at":"2016-08-01 15:53:59"
        },
        {  
            "id":"2",
            "contact_name":"qweryyy",
            "user_phone_number":"03331524145",
            "created_at":"2016-08-01 15:53:59"
        },
        {  
            "id":"3",
            "contact_name":"qweryyy",
            "user_phone_number":"03331524145",
            "created_at":"2016-08-01 15:53:59"
        }
    ]
}

以下是获取用户数组并返回以显示json响应的代码:

 if ($result) {
        $this->conn = new PDO("mysql:host=$servername;dbname=$dbname",   
 $username, $password);
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, 
PDO::ERRMODE_EXCEPTION);
        $stmt = $this->conn->prepare("SELECT * FROM contact WHERE 
user_phone_number = '$user_phone_number' ");
        //$stmt->bind_param("s", $phone_number);
        $stmt->execute();
        $user = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
        $user = $stmt->fetchAll();
        //print_r($user);
        return $user;

    } else {
        return false;
    }

SHOW json回复:

if ($user) {
    $string = '';
    $cart = array();
    $response["status"] = TRUE;
    for($x=0;$x<count($user);$x++)
    {
        $string = $user[$x];
        array_push($cart, $string);

    }

        echo json_encode(array($cart));


}

显示所需输出的任何帮助??

1 个答案:

答案 0 :(得分:0)

$query = 'SELECT * FROM contact WHERE user_phone_number = "'.$user_phone_number.'"';
$result = mysql_query($query) or trigger_error($query.'<br>'.mysql_error(),E_USER_ERROR);
$list = Array();
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
  $list[] = $row;
}
$cart = Array(
  'unique_id' => '579992ffd1';
  'user' => $list;
);
echo json_encode($cart);