简体   繁体   中英

Get names data in alphabetical order with section headings in php mysql

I have a table like below, was trying to get the data in JSON format 2D array but no success. I've tried different methods, but unable to achieve it. Please guide me to get the result.

***Forgot to upload the code, here is the updated question with my trial code.

id   company_name 
-----------------
1    Alexa          
2    Cisco          
3    Blackberry     
4    Amazon         
5    Deka           
6    Colgate        
7    Dell           
8    BBC 

I want to get that data like below in 2D JSON format array.

[
    {
      id: 1,
      heading: 'A',
      data: [
        {id: 4, text: 'Amazon'},
        {id: 1, text: 'Alexa'},
      ]
    },
    {
      id: 2,
      heading: 'B',
      data: [
        {id: 8, text: 'BBC'},
        {id: 3, text: 'Blackberry'},
      ]
    },
    {
        id: 3,
        heading: 'C',
        data: [
          {id: 2, text: 'Cisco'},
          {id: 6, text: 'Colgate'},
        ]
    },
    {
        id: 4,
        heading: 'D',
        data: [
          {id: 5, text: 'Deka'},
          {id: 7, text: 'Dell'},
        ]
    }
]

I am trying with the below code, but not yet succeed. I am still trying, if anyone come up with a help, would be very much appreciated.

$query = mysqli_query($dblink,"SELECT id,company_name FROM company_names ORDER BY company_name");

$data = array();
while($row = mysqli_fetch_assoc($query)) {
  $id = $row["id"];
  $letter = strtolower(substr($row["company_name"],0,1));
  if(is_numeric($letter)) $letter = "0-9";
  if(!isset($data[$letter])){
  $data[$letter] = array();}
  $data[$letter][] = $row["company_name"];
}

echo json_encode($data);

Really, I added to your code only setting additional columns to the result array.

$data = array();
$id = 1;
while($row = mysqli_fetch_assoc($query)) {
  $letter = strtoupper($row["company_name"]{0});
  if(is_numeric($letter)) $letter = "0-9";
  if(!isset($data[$letter])) {
     $data[$letter]['heading'] = $letter;
     $data[$letter]['id'] = $id++;
  }
  $data[$letter]['data'][] = $row;
}

echo json_encode($data);

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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