-2

Im working with a JSON file that checks, if a user is typing.

Is there any reason why this would not work?

  // Array of WP_User objects.
  foreach ( $user_query as $user ) {
    $result['whotyping'] = $user_info->whotyping;
    $result['typingto'] = $user_info->typingto;
    $result['typing'] = $user_info->typing;
  }

  echo json_encode($result);

I thought this would work, but it returns nothing by an error.

How do I solve this problem?

  // Array of WP_User objects.
  foreach ( $user_query as $user ) {
    $result['whotyping'] = $user_info->whotyping;
    $result['typingto'] = $user_info->typingto;
    $result['typing'] = $user_info->typing; 
    echo json_encode($result);
  }
Emma
  • 27,428
  • 11
  • 44
  • 69
Mic
  • 331
  • 1
  • 2
  • 14
  • 1
    not sure what you are asking here, your loop is pointless, the variables inside `$result` get replaced on each loop iteration so the content of `$result` will always be the value of the last `$user` in the loop. – Julien Apr 23 '19 at 02:25
  • thats not 100% correct. For each user there is in users, return the following 3 results from that user and encode it as a json. im sure its possible to do. – Mic Apr 23 '19 at 02:28
  • show us the value of `$user_query` – A l w a y s S u n n y Apr 23 '19 at 02:31
  • You need to put the results in an array, not just overwrite the same elements each time. – Barmar Apr 23 '19 at 02:34

1 Answers1

2

You should make an array of results.

// Array of WP_User objects.
$results = array();
foreach ( $user_query as $user ) {
    $result = array();
    $result['whotyping'] = $user_info->whotyping;
    $result['typingto'] = $user_info->typingto;
    $result['typing'] = $user_info->typing;
    $results[] = $result;
}

echo json_encode($results);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Barmar
  • 741,623
  • 53
  • 500
  • 612