-1

I'm trying to convert database value to json I had do some array before encode to json, but it not return like what i want, someone please help me My code is some thing like this

  function createDataJson($ref){
  $master_data = array();
  // $data = array();
  $sql = mysql_query("SELECT DISTINCT dataCode FROM tbl_master WHERE dataRefServices = '$ref'");
  if(mysql_num_rows($sql)){
    while($row = mysql_fetch_assoc($sql)){
      $dataCode = $row['dataCode'];
      $sql2 = mysql_query("SELECT DISTINCT asKey,asValue FROM tbl_master WHERE dataCode = '$dataCode' AND dataRefServices = '$ref'");
      if(mysql_num_rows($sql2)){
        while ($row2 = mysql_fetch_assoc($sql2)) {
          $asKey = $row2['asKey'];
          $asValue = $row2['asValue'];
          $data->$asKey=$asValue;
        }
          $dat[] = $data;
      }
      $master_data = $dat;
    }
  }

  return json_encode($master_data);
}

and it return like this, it just duplicate the last array

    [
  {
    "code": "IT - 0004",
    "main": "12",
    "child": "14",
    "name": "Laptop",
    "brand": "Lenovo"
  }, {
    "code": "IT - 0004",
    "main": "12",
    "child": "14",
    "name": "Laptop",
    "brand": "Lenovo"
  }
]

The format I'm looking for is something like this:

  [
    {
    "code": "IT - 0001",
    "main": "12",
    "child": "14",
    "name": "Pavillion 15",
    "brand": "Asus"
  }, {
    "code": "IT - 0002",
    "main": "12",
    "child": "14",
    "name": "Envy 13",
    "brand": "HP"
  }
 ]

From this table:

enter image description here

Please help me, really looking for it

can someone assist me on this , please. i'm stuck here. hehehe

Haz Wan
  • 1
  • 1
  • 2
    First get the data from database as array then use json_encode() method to convert that array into json. – RopAli Munshi Dec 12 '18 at 04:31
  • Possible duplicate of [Returning JSON from a PHP Script](https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script) – kgbph Dec 12 '18 at 06:28

1 Answers1

0

Use json_encode to convert array to json.

echo json_encode($array_of_data_from_database);

This will send the JSON Data as response.

Nero
  • 153
  • 8
Tej
  • 175
  • 7
  • [ { "code": "IT - 0004", "main": "12", "child": "14", "name": "Laptop", "brand": "Lenovo" }, { "code": "IT - 0004", "main": "12", "child": "14", "name": "Laptop", "brand": "Lenovo" }, { "code": "IT - 0004", "main": "12", "child": "14", "name": "Laptop", "brand": "Lenovo" }, { "code": "IT - 0004", "main": "12", "child": "14", "name": "Laptop", "brand": "Lenovo" } ] – Haz Wan Dec 12 '18 at 14:07
  • it return that way – Haz Wan Dec 12 '18 at 14:08