PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How to JSON encode a user array using PHP?

 July 23, 2022     json, jsonencoder, php     No comments   

Issue

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);
  }


Solution

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);


Answered By - Barmar
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing