php - 列出多维数组

标签 php mysql multidimensional-array

我已经做了一个查询,从其他表中获取相同 id 下的所有数据。同一 id 下有超过 2 个数据。

我需要像数组一样显示同一 id 下的所有数据。

这是我的 sql 查询:

  "SELECT incident.*,entry.*,fighter.* 
  FROM register_incident AS incident JOIN 
  register_entry_points AS entry 
  ON entry.incident_id = incident.incident_id 
  JOIN add_fire_fighters AS fighter 
  ON entry.entrypoint_id = fighter.entry_point_id 
  WHERE incident.incident_id=:incident_id"

我收到这样的回复,

 "data":[
 {

  "incident_id": "5",
  "user_id": null,
  "entrypoint_id": "20",
  "entry_points": "New Entry1111",
  "comments": "Comment1",
  "fighter_id": "67",
  "entry_point_id": "20",
  "cylpressure": null,
  "time_in": null,
  "time_out": null,
  "duration": null,
  "notes": null
},
{
  "incident_id": "5",
  "user_id": "16",
  "entrypoint_id": "20",
  "entry_points": "New Entry1111",
  "comments": "Comment1",
  "fighter_id": "68",
  "entry_point_id": "20",
  "cylpressure": "300",
  "time_in": "10:30:00",
  "time_out": "11:45:00",
  "duration": "01:15",
  "notes": "Test"
},

但我需要像这样显示它,

"data": [
   {
  "incident_id": "5",
  "user_id": null,
  "entrypoint_id": "20",
  "entry_points": "New Entry1111",
  "comments": "Comment1",
  "fighter":{
    {
  "fighter_id": "67",
  "entry_point_id": "20",
  "cylpressure": null,
  "time_in": null,
  "time_out": null,
  "duration": null,
  "notes": null
   },
   {

  "fighter_id": "68",
  "entry_point_id": "20",
  "cylpressure": null,
  "time_in": null,
  "time_out": null,
  "duration": null,
  "notes": null

   }
   }
   }]

这怎么可能?

最佳答案

如果我从具有一个或多个 1:n 关系的查询中获取 ResultSet,我会像此示例一样获取结果。

$Result = array();
foreach($Records as $Record) {
  // key 1
  $key1 = $Record['incident_id'];
  if(isset($Result[$key1])) {
    $cuIncident=$Result[$key1];
  }
  else {
    $cuIncident=array(
      'incident_id' => $key1,
      'user_id'     => $Record['user_id'],
      //......
      'fighter'     => array()
    );
    $Result[$key1] = $cuIncident;
  }
  // key 2
  $key2 = $Record['fighter_id'];
  if(isset($cuIncident['fighter'][$key2])) {
    $cuFighter = $cuIncident['fighter'][$key2];
  }
  else {
    $cuFighter = array(
      'fighter_id'      => $key2,
      'entry_point_id'  => $Record['entry_point_id'],
      //......
      'key3array'       => array()
    );
    $cuIncident['fighter'][$key2] = $cuFighter;
  }
  // key 3
  // ....

如果键是多值键,则必须将这些键组合起来,例如:

  $key3 = $Record['key3prop1']."/".$Record['key3prop2'];
  if(isset($key3Array[$key3])) ......

关于php - 列出多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43086297/

相关文章:

来自三个表的 SQL 查询的 PHP 多数组 (JSON)

php - 如何使用 shuffle 解决随机问题

php - 无法使用 try catch block 捕获 PHP file_get_contents 错误

mysql - 允许用户可以查看其他用户创建的存储过程

c - 如何调用一个以指针为参数的函数

C++ 多维 vector 追加

PHP XML IE 问题

java - 无法识别阿拉伯字符

mysql - 根据孙子显示父计数

php - Symfony 2 : SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry