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


How do i create json array of object usingthe php code?

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

您希望组织数组的方式略有不同。

试试这个

$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 之前,您将根据需要对它们进行分组。