0

I need to compare array of users with by database list of users. If database does not have data that is in array, I have to remove it. I have done this, but it prints like object, but i need to print it like array How it is:

{"user":"1"}{"user":"2"}{"user":"3"}{"user":"4"}

How it should be:

[{"user":"1"}{"user":"2"}{"user":"3"}{"user":"4"}]

I

$allUsers = [
    "1",
    "2",
    "3",
    "4",
    "5",
];



foreach ($allUsers as $value) {
    $users = [];

    $sql = "select * from posts where user=:user order by id asc";
    $data = $db->prepare($sql);
    $data->execute(array(':user' => $value));
    $allpost = $data->fetchAll();
    $count = $data->rowCount();
   if ($count !== 0) {
       foreach($allpost as $user) {
           $users = [
           'user' => $user['user']
           ];
       }
       echo json_encode($users);
   }
}
shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
Arboker
  • 3
  • 4
  • 1
    why are you looping through posts to get your user data? you can avoud a foreach loop when using in your sql `where users in(id1,id2,id3,id4)` – Sysix Oct 14 '20 at 18:14
  • Pass true as the second parameter to json_encode – imposterSyndrome Oct 14 '20 at 18:20
  • Does this answer your question? [json\_encode sparse PHP array as JSON array, not JSON object](https://stackoverflow.com/questions/11195692/json-encode-sparse-php-array-as-json-array-not-json-object) – imposterSyndrome Oct 14 '20 at 18:22
  • @jameson2012 no, because it prints data not like I want (You can see how I want in question) – Arboker Oct 14 '20 at 18:53

0 Answers0