Как я могу получить массив объектов JSON с помощью PHP?

0

Это мой код для получения данных формата json. Но это не точный формат, который мне нужен. Может ли кто-нибудь помочь мне решить эту проблему.

 while ($row = $get_postid->fetch_array())
            {
                $comment_id[]=$row['comment_id'];
                $id[]=$row['post_id'];
                $user_id[]=$row['user_id'];
                $comm_description[]=$row['comment_description'];
                $time[]=$row['creation_date'];


            }

            for($i=0;$i<count($user_id);$i++)
            {

                $user=mysqli_query($con,"select * from Wheel_User where user_id='$user_id[$i]'");

                if(mysqli_num_rows($user)==0)
                {
                    //For failure status if session id is wrong.
                    http_response_code(500);
                    echo json_encode(array("error_code"=>"500","error_message"=>"Sorry, post id does not exists.".die()));
                }

                else
                {

                    while ($row = $user->fetch_array())
                    {

                        $users[$i]['id']=$row['user_id'];
                        $pro_image_url[$i]=$row['profile_image_url'];
                        $users[$i]['title']=$row['user_name'];
                        $users[$i]['about_user']="";
                        $short_image_url[$i]=str_replace('_b','_t',$pro_image_url[$i]);
                        $short_image_url[$i]=str_replace('/images/','/thumbnails/',$short_image_url[$i]);
                        $users[$i]['short_image_url']=$short_image_url[$i];
                    }
                }  
            }


        echo str_replace('\/','/', json_encode(array("id"=>$id,"description"=>$comm_description,"time"=>$time,"user"=>$users)));

Результат приведенного выше кода аналогичен приведенному в json формате

{
 id: [3]
  0:  "1000"
  1:  "1000"
  2:  "1000"

description: [3]
  0:  "hai hello bye"
  1:  "helloooooo"
  2:  "haiiiiiii"

time: [3]
  0:  "0000-00-00 00:00:00"
  1:  "0000-00-00 00:00:00"
  2:  "0000-00-00 00:00:00"

user: [3]
 0:  {
    id: "1234"
   title: "chetan"
   about_user: ""
   short_image_url: "http://54.169.40.195/wheel/wheel/service/testing/chetan/audio/c71dfe45421b2864476a0bde257f0a57e72084783ce859e26595599670904907.mp3"
   }
   1:  {
   id: "4321"
   title: ""
   about_user: ""
   short_image_url: "http://localhost/phpmyadmin/#PMAURL-26:tbl_change.php?db=wheel&table=Wheel_User&server=1&target=&token=9f24bb1783394ac86321c4f15ceacf7a"
  }
  2:  {
  id: "5678"
  title: "dinesh"
  about_user: ""
  short_image_url: "http://localhost/phpmyadmin/#PMAURL-24:tbl_change.php?db=wheel&table=Wheel_User&server=1&target=&token=9f24bb1783394ac86321c4f15ceacf7a"
}

}

Но я хочу получить результат в следующем формате

{
 id:"1000",
 description:"post details of user",
time:"0000-00-00 00:00:00",      
user:{
    id: "1234"
   title: "chetan"
   about_user: ""
   short_image_url: "http://54.169.40.195/wheel/wheel/service/testing/chetan/audio/c71dfe45421b2864476a0bde257f0a57e72084783ce859e26595599670904907.mp3"
   }

}
{
 id:"1000",
 description:"post details of user",
time:"0000-00-00 00:00:00",      
user: {
    id: "4321"
   title: "prasanna"
   about_user: ""
   short_image_url: "http://54.169.40.195/wheel/wheel/service/testing/chetan/audio/c71dfe45421b2864476a0bde257f0a57e72084783ce859e26595599670904907.mp3"
   }

}

Может ли кто-нибудь помочь мне решить эту проблему?

  • 1
    Так json_decode($jsonString, true) ? Даже не стоит ответа.
Теги:

1 ответ

1
Лучший ответ

Вы должны перестроить свой массив, чтобы получить желаемый результат. Попробуйте заменить последнюю строку кода следующим образом:

$objectArray = array();
for($i=0;$i<count($id);$i++) {
    $objectArray[$i]['id'] = $id[$i];
    $objectArray[$i]['description'] = $comm_description[$i];
    $objectArray[$i]['time'] = $time[$i];
    $objectArray[$i]['user'] = $users[$i];
}

echo str_replace('\/','/', json_encode($objectArray)));
  • 0
    Большое спасибо, это работает отлично. Просто я хочу спросить, нужно ли мне помещать эти объекты в массив с именем "comment", где я должен добавить это ключевое слово "comment"?
  • 0
    Я думаю, что вы имеете в виду: echo str_replace ('\ /', '/', json_encode (array ('comment' => $ objectArray))));
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню