0

I have done a query for getting all data's under same id from other table.There are more than 2 data's under same id.

I need to display all data 's under same id like an array.

Here is my sql query:

  "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"

I get a response like,

 "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"
},

But i need to display it like,

"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

   }
   }
   }]

How it is possible?

Reshma
  • 189
  • 2
  • 5
  • 18
  • 4
    Possible duplicate of [Group a multidimensional array by a particular value?](http://stackoverflow.com/questions/2189626/group-a-multidimensional-array-by-a-particular-value) – Alex Shesterov Mar 29 '17 at 06:52

1 Answers1

0

If I get a ResultSet out of a Query with one or more 1:n relationships, I take the result like this sample.

$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
  // ....

If a key is a multi value key, you have to combine these keys like:

  $key3 = $Record['key3prop1']."/".$Record['key3prop2'];
  if(isset($key3Array[$key3])) ......
Holger
  • 899
  • 2
  • 7
  • 12