Home:ALL Converter>Rename fetched mysql then encode to JSON

Rename fetched mysql then encode to JSON

Ask Time:2013-05-16T19:51:25         Author:SpeedfreakR

Json Formatter

I want my own table names endoced to JSON and do not want to use the mysql table names. In case I rename the column I only have to rename them in de php file.

In short:

  • run query
  • fetch mysql
  • rename column from output
  • encode to JSON

This is what I have now:

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $rows['feed'] =  $row;
    sendResponse(200, json_encode($rows));
}

I want to know: How to open the fetched array and change the column names and rename them to my own name and then send them to JSON

EDIT: I edited my row

 $result = mysql_query("SELECT * FROM od_common.debiteur WHERE SORT_NAAM LIKE '%comp%'");



while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

$deb_nr = $row['DEB_NR'];
$deb_naam = $row['DEB_NAAM'];
$deb_adres = $row['DEB_ADRES'];



$rows['klant'] = array('klantnr' => $deb_nr, 'klntnm' => $deb_naam, 'adrs'      =>         $deb_adres);





sendResponse(200, json_encode($rows));
}
}

I get al most what I want. But I want this:

 {
   "klant": [
    {
      "klntnr": "10010",
      "klntnm": "Company1",
  "adrs": "street1"
},
{
  "klntnr": "25071",
  "klntnm": "Company2",
  "adrs": "street2"
},
{
  "klntnr": "25247",
  "klntnm": "Company3",
  "adrs": "street3"
},
{
  "klntnr": "25454",
  "klntnm": "Company4",
  "adrs": "street4"
},
{
  "klntnr": "25601",
  "klntnm": "Company5",
  "adrs": "street5"
}
  ]
 }

Not this:

{  "klant": {
 "klantnr": "10010",
 "klntnm": "Company1",
 "adrs": "street1"
   }
  }{
  "klant": {
    "klantnr": "25071",
    "klntnm": "Company2",
    "adrs": "street2"
  }
 }{
  "klant": {
    "klantnr": "25247",
    "klntnm": "Company3",
    "adrs": "street3"
  }
 }{
   "klant": {
    "klantnr": "25454",
    "klntnm": "Company4",
    "adrs": "street4"
  }
 }{
  "klant": {
    "klantnr": "25601",
    "klntnm": "Company5",
    "adrs": "street5"
  }
 }

Author:SpeedfreakR,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/16586651/rename-fetched-mysql-then-encode-to-json
yy