我有 json 数组数据,需要使用 php 在电容器和 DG 的 foreach 循环中获取



我想使用 php 获取以下 json 数据:

 $str ='{
  "site_Id": "1",
  "site_Name": "Guajarat",
  "site_Address": "Emami",
  "site_StartDate": "10 / November / 2017   To   11 / November / 2017",
  "Capacitor": [
  {
  "checkList_Id_PointNo": "1",
  "checkList_Name": "APFC Panel doors and covers properly closed",
  "checkList_Status": "Not OK",
  "checkList_Remark": "Remark 1",
  "checkList_Photo": "11Capacitor BankCapacitor Name1",
  "fk_equipmentType": "Capacitor Bank"    
  },
  {
  "checkList_Id_PointNo": "2",
  "checkList_Name": "APFC Panel door locks working properly.",
  "checkList_Status": "Not OK",
  "checkList_Remark": "Remark ",
  "checkList_Photo": "11Capacitor BankCapacitor Name2",
  "fk_equipmentType": "Capacitor Bank"
  }
  ],
 "DG": [
  {
  "checkList_Id_PointNo": "1",
  "checkList_Name": "Substation earthing layout clearly making the position or earthing pits with identification number and the route of earthing lead / strip",
  "checkList_Status": "Not OK",
  "checkList_Remark": "Remark gg",
  "checkList_Photo": "12EarthingDG Earthing1",
  "fk_equipmentType": "Earthing"
  },
  {
  "checkList_Id_PointNo": "2",
  "checkList_Name": "All earhting pits should have identification number as indicated in earthing layout written over them with permanent paint",
  "checkList_Status": "Not OK",
  "checkList_Remark": "Remark gg",
  "checkList_Photo": "12EarthingDG Earthing2",
  "fk_equipmentType": "Earthing"
  }
  ]
 }';

到目前为止,我只对电容器进行了编码,但我还需要从同一个循环中获取电容器和 DG。下面是 foreach 循环,我只从中获取电容器的数据,但在该循环中我还需要同时获取 DG。

foreach ($json['Capacitor'] as $field => $value) {
    $id = $json['Capacitor'][$field]['checkList_Id_PointNo'];
    $name = $json['Capacitor'][$field]['checkList_Name'];
    $status = $json['Capacitor'][$field]['checkList_Status'];
    $remark = $json['Capacitor'][$field]['checkList_Remark'];
    $photo = $json['Capacitor'][$field]['checkList_Photo'];
    echo $id.'<br>'.$name.'<br>'.$status.'<br>'.$remark.'<br>'.$photo.'<br><br>';
}

你可以像下面这样做:-

<?php
$json = json_decode($str,true);
print_r($json);

foreach ($json as $value) {
  if(is_array($value)){
    foreach($value as $val){
       $id = $val['checkList_Id_PointNo'];
       $name = $val['checkList_Name'];
       $status = $val['checkList_Status'];
       $remark = $val['checkList_Remark'];
       $photo = $val['checkList_Photo'];
       echo "INSERT INTO table (id, name, status, remark, photo) VALUES ('$id', '$name', '$status','$remark','$photo')".PHP_EOL; // i have printed it so that you can see that it's printing perfectly.
    }
  }
}

输出:- https://eval.in/898497

最新更新