繁体   English   中英

有没有办法使用 php 创建对象数组并从中创建 json 文件

[英]Is there a way to create an array of objects using php and create an json file from it

我正在尝试使用来自多个表的数据创建一个对象数组,假设有一个保存患者数据的表,还有一个保存诊断的表,以及每个入院患者的药物,我需要创建一个具有以下 output 的对象数组。 截屏

我必须编写以下代码

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


     
     }
?>

它给出了以下 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"
        }
      ]
    }
  ]
}

我的桌子是

nhif_data ---- nhif_data ,

实验室----实验室

叶病——叶病

dawa_zilizotoka ---- dawa_zilizotoka

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 / 对象数组,等等。

您只需要从数据库中获取记录,根据需要进行子嵌套,append 将记录保存到数组中,只需 'json_encode()'; 使用 'json_decode()',你最终会得到一个对象数组。

$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

以下应该可以更好地理解机制;

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", ], ], 
])));

或者,使用较新的 PHP 版本,我希望您可以简单地准备/构造数组并使用类似的东西将其对象化;

$JSON = (object) $JSONItem;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM