1

I need help to get below output from my database..

{
   "CustomerAddress":[
      {
         "customer_address_id":"101",
         "address_category_name":"Other",
         "address_name":"Nasser Vocational Training Center, Jao",
         "Details":[
            {
               "address_details_id":"1",
               "address_details_text":"ADD-101-1"
            },
            {
               "address_details_id":"2",
               "address_details_text":"ADD-101-1"
            }
         ]
      },
      {
         "customer_address_id":"109",
         "address_category_name":"Other",
         "address_name":"Nasser Vocational Training Center, Jao",
         "Details":[
            {
               "address_details_id":"7",
               "address_details_text":"ADD-101-2"
            }
         ]
      }
   ]
}

each CustomerAddress will have one or more Details. I tried below but it's repeating the Departments as you can see here:

https://www.softnames.com/ws/temp.php?customer_id=5235

The customer_address_id 101 has four details which should comes under the CustomerAddress but it's just repeating it separating.

Here is my PHP:

$jsonData = array();

while ($mysql_row = $mysql_query->fetch())
{
  $jsonData[] = array(
      'CustomerAddress' => 
      array('customer_address_id' => $mysql_row['customer_address_id'],
      'address_category_name' => $mysql_row['address_category_name'],
      'address_name' => $mysql_row['address_name'],
      'Details' => array(
      'address_details_id' => $mysql_row['address_details_id'],
      'address_details_text' => $mysql_row['address_details_text'])
      )
  );
}

Kindly help..

Thanks Jassim

Jassim Rahma
  • 93
  • 1
  • 3
  • 13
  • `echo json_encode($jsonData);` – Barmar Jun 27 '17 at 01:13
  • You're adding a new entry to `$jsonData` for every row. If it has the same `customer_address_id` as a previous row, you should just be appending to the `Details` array, not creating another row. See http://stackoverflow.com/questions/35473174/creating-one-array-from-another-array-in-php – Barmar Jun 27 '17 at 01:15
  • bu how can I apply the same to mysql? $result = []; foreach($MainArray as $record){ $result[$record['Machine_Name']][] = $record; } echo '
    '; print_r($result);
    – Jassim Rahma Jun 27 '17 at 01:30
  • There's little difference between looping through an array as in the question I linked to, and looping through the results of a query. You should be able to use the same logic. – Barmar Jun 27 '17 at 16:59
  • I tried all ways but never worked for me :( – Jassim Rahma Jun 27 '17 at 23:04

0 Answers0