How to create an array of objects In PHP using a while loop -


Hi, I am trying to return all the "people" from my database and then the "person" Create an object, then at the end of each loop, add the person to the array while the outside of the loop I called the encoding again.

Attached is my current code below:

  class person {public $ firstName = ""; Public $ lastName = ""; } $ People = array (); $ Result = mysqli_query ($ con, "select from people"); While ($ line = mysqli_fetch_array ($ result)) {$ firstName = $ line ['first name']; $ LastName = $ line ['lastName']; $ E = new person (); $ E- & gt; First name = $ firstName; $ E- & gt; Last name = $ lastName; Array_push ($ people, $ E); } Json_encode ($ people);  

Many thanks

This does not seem to be the question here, But in this case maybe more useful for you.

In addition, see your nomenclature, you have called your class "person" and have given it immediately in the form of "person". The PHP is flexible about the case, but this may cause problems later in your program. Are there.

Finally, json_encode simply encodes an object if you want to display results or push it to be used on the browser, you have to echo it out:

  header ('content-type: application / jason'); Echo json_encode ($ people);  

Comments