1

How do I convert from my PHP array (mysql_fetch_array) to a declared PHP Class then encode that to json format string. My array:

    while ($rows = mysql_fetch_array($result, MYSQL_ASSOC)){
    $patient[] = array( 'id' => $rows['id'],
                        'name' => $rows['name'], 
                        'sex' => $rows['sex'], 
                        'civil_status' => $rows['civil_status'],
                        'age' => $rows['age'], 
                        'type_of_admission' => $rows['type_of_admission'],
                        'admission_diagnosis' => $rows['admission_diagnosis'],
                        'date_admitted' => $rows['date_admitted']);
          }

My declare PHP Class

  class Person
    {
     public $id;
     public $name;
     public $sex;
     public $civil_status;
     public $age;
     public $type_of_admission;
     public $admission_diagnosis;
     public $date_admitted;
  }
2
  • possible duplicate of Convert Array to Object PHP Commented Sep 20, 2013 at 1:42
  • Why do you need to populate a class before calling json_encode()? Just json_encode the array. Commented Sep 20, 2013 at 2:18

2 Answers 2

1

I think you are looking for mysql_fetch_object:

while ($row = mysql_fetch_object($result, 'Person')){

    $json_rows[] = json_encode($row);

}

Also, you should be using mysqli, which has the same basic concept.

Sign up to request clarification or add additional context in comments.

2 Comments

I believe this will probably help either: stackoverflow.com/questions/9896254/php-class-instance-to-json
@AlejandroIván tnx I look to it now
0

just retype to (object)

$object = (object) $array_name;

for json_encode.

1 Comment

i want to place that $patient array to Person class then json_encode, how do i do it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.