如何使用PHP代码创建对象的json数组?

时间:2015-01-24 06:41:41

标签: php json

for($i=0;$i<count($storetag);$i++){
    $user=mysqli_query($con,"select user_id,profile_image_url from Wheel_User where user_id='$storetag[$i]'");

    if(mysqli_num_rows($user)==0){
        //For failure status if session id is wrong.
        //http_response_code(404);
        echo json_encode(array("status"=>"404","error"=>"Sorry, post id does not exists.".die()));
    }
    else{
        $json_responce1=array();
        while ($row = $user->fetch_array()){
            $row_array['user_id'][$i]=explode(',',$row['user_id']);
            $row_array['profile_image_url'[$i]=$row['profile_image_url'];
        }
    }  
}

array_push($json_responce1,$row_array); 
echo str_replace('\/','/', json_encode(array($json_responce1)));

返回以下JSON

{
user_id: [3]

  "1234",
  "31332",
  "12412"


profile_image_url: [3]

      "localhost/1234.com",
      "localhost/2345.com",
      "localhost/3456.com"

}

但我想要像这样的json格式

"user_id":[
    {
        "id":"1234",
        "url":"localhost/1234.com"
    },
    {
        "id":"1234",
        "url":"localhost/1234.com"
    },
    {
        "id":"1234",
        "url":"localhost/1234.com"
    }
]

1 个答案:

答案 0 :(得分:0)

您希望将阵列组织略有不同。

试试这个

$row_array['user_id'][$i]['id']=explode(',',$row['user_id']);
$row_array['user_id'][$i]['url']=$row['profile_image_url'];

所有内容都应该在user_id中,然后将$i放在$id$url之前,您将根据需要对它们进行分组。