1

I'm trying to create an array of objects with data coming from multiple tables, lets say there is table that hold patient data and there is table that hold diagnosis, and medicine for every patient that admitted to clinic, and i need to create an array of objects with the following output. Screen shot

And i have to write the following code

 <?php
    // Db configs.
    define('HOST', 'localhost');
   define('PORT', 3306);

    define('DATABASE', 'new_nhif');
    define('USERNAME', 'root');
    define('PASSWORD', '');

error_reporting(E_ALL);
ini_set('display_errors', 1); 

$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);

$sql = sprintf(
        'SELECT 
                nh.MembershipNo,
                nh.FullName,
                nh.id as nhid,
                lb.labrequest,
                fd.diagnosis,
                fd.DiseaseCode,
                fd.CreatedBy as fdcrb,
                dz.name

            FROM nhif_data AS nh 
            LEFT JOIN laboratory AS lb ON lb.re_id = nh.id 
            LEFT JOIN foliodisease AS fd ON fd.re_id = nh.id
            LEFT JOIN dawa_zilizotoka AS dz ON dz.re_id = nh.id
            WHERE  lb.re_id = nh.id
            AND  fd.re_id = nh.id
            AND  dz.re_id = nh.id
            -- GROUP BY nh.MembershipNo
           '
);

$obj = new stdClass;


$result = $connection->query($sql);

$vipimo = array();
$dawa = array();
$all = array();


if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            
            // print_r(json_encode(['entities'=> $row],JSON_PRETTY_PRINT));

             $obj->MembershipNo = $row['MembershipNo'];
             $obj->FullName = $row['FullName'];

             $id = $row['nhid'];
            

             $sql2 = "SELECT * FROM foliodisease WHERE re_id ='$id'";
        
             $result1 = $connection->query($sql2);
            

             if ($result1->num_rows > 0) {

                while($row2 = $result1->fetch_assoc()) {
                       
                        $vipimo['diagnosis']= $row2['diagnosis'];
                        $vipimo['DiseaseCode']= $row2['DiseaseCode'];

                        $obj->FolioDiseases[] =  $vipimo;
                }
            
             }


             $sql3 = "SELECT * FROM dawa_zilizotoka WHERE re_id = $id";
        
             $result3 = $connection->query($sql3);
            

             if ($result3->num_rows > 0) {

                while($row3 = $result3->fetch_assoc()) {
                       
                        $dawa['name']= $row3['name'];

                        $obj->FolioItems[] =  $dawa;
                }
            
             }


             $all[] = $obj;

             }

             print_r(json_encode(['entities'=> $all], JSON_PRETTY_PRINT));


     
     }
?>

And it give out the following output

{
  "entities": [
    {
      "MembershipNo": "602124502",
      "FullName": "Omari M Simba",
      "FolioDiseases": [
        {
          "diagnosis": "typhoid",
          "DiseaseCode": "J54"
        },
        {
          "diagnosis": "homa",
          "DiseaseCode": "L54"
        },
        {
          "diagnosis": "malaria",
          "DiseaseCode": "b54"
        }
      ],
      "FolioItems": [
        {
          "name": " Fluticasone furoate\t"
        },
        {
          "name": " Acyclovir  Eye ointment\t"
        },
        {
          "name": " Acyclovir\t"
        },
        {
          "name": " Acyclovir\t"
        }
      ]
    },
    {
      "MembershipNo": "602124502",
      "FullName": "Omari M Simba",
      "FolioDiseases": [
        {
          "diagnosis": "typhoid",
          "DiseaseCode": "J54"
        },
        {
          "diagnosis": "homa",
          "DiseaseCode": "L54"
        },
        {
          "diagnosis": "malaria",
          "DiseaseCode": "b54"
        }
      ],
      "FolioItems": [
        {
          "name": " Fluticasone furoate\t"
        },
        {
          "name": " Acyclovir  Eye ointment\t"
        },
        {
          "name": " Acyclovir\t"
        },
        {
          "name": " Acyclovir\t"
        }
      ]
    }
  ]
}

My tables are

nhif_data ---- nhif_data ,

laboratory ---- laboratory,

foliodisease --- foliodisease ,

dawa_zilizotoka ---- dawa_zilizotoka

3
  • Probably a reference issue. You're using the same object you created at the start, so any modifications made to it are reflected in your array. Move the object creation inside the while loop (at the beginning) so that a new instance is created in each iteration. Commented May 26, 2021 at 14:25
  • Why sprintf() if you aren't using any placeholders? That is an entirely useless call. Iterated queries are a no-no. Commented May 26, 2021 at 14:28
  • Yeah true its works now i move the object creation inside a while loop and it works Commented May 26, 2021 at 14:30

1 Answer 1

1

You don't need to create an object array for the desired output, 'json_encode()' basically objectifies anything, meaning, no matter what you store with 'json_encode()' function, 'json_decode()' will always return you an object/array of objects, and so on.

All you need to fetch the records off the database, make child nesting as required, append the record to an array, and just 'json_encode()'; with 'json_decode()', you will end up with an array of objects.

$JSONItem = []; // Initialize the array

while($Record = $Query->fetch_assoc()){ // Iterate through main recordset
    ...subsequent child query   
    // Iterate though child recordset
    while($ChildRecord = $ChildQuery->fetch_assoc())$Record["Child"][] = $ChildRecord; // Append child node to main record
    $JSONItem[] = $Record; // Append record for JSON conversion
}

var_dump(json_decode(json_encode($JSONItem))); // This should return an array of ojects

Following should allow a better understanding of the mechanism;

var_dump(json_decode(json_encode([
    ["ID" => 1, "Name" => "Apple", "Source" => ["Name" => "Amazon", "URL" => "http://Amazon.Com", ], ], 
    ["ID" => 2, "Name" => "Banana", "Source" => ["Name" => "eBay", "URL" => "http://eBay.Com", ], ], 
    ["ID" => 3, "Name" => "Carrot", "Source" => ["Name" => "GearBest", "URL" => "http://GearBest.Com", ], ], 
])));

Or, with newer PHP version, I hope you can simply prepare/construct the array and objectify it with something like;

$JSON = (object) $JSONItem;
Sign up to request clarification or add additional context in comments.

Comments

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.