I have a table in my server database with the following columns:
|---category--|---name---|---description---|
So, lets say for example that we have the following data inside the table:
|---CategoryA--|---name1---|---description1---|
|---categoryB--|---name2---|---description2---|
|---categoryA--|---name3---|---description3---|
|---categoryA--|---name4---|---description4---|
I would like to create a .php file, and when i call it from my Android app i would like to get a JSON as response. The json file would like to have the following format:
{
"CategoryA":[
{"name":"name1","description":"description1"},
{"name":"name3","description":"description3"},
{"name":"name4","description":"description4"}
],
"KatigotiaB":[
{"name":"name2","description":"description2"}
]
}
I have created a .php file that returns me the data in JSON format, but not in the specific format i want. Here is my .php file:
<?php
header('content-type: text/html; charset=utf-8');
try {
$pdo = new PDO('mysql:host=****;dbname=****', '****', '****', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$stmt = $pdo->prepare("SELECT * FROM `db`.`table`;");
$stmt->execute();
$results = array();
while ($obj = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($results, $obj);
}
function replace_unicode_escape_sequence($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UTF-16BE');
}
$str = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', json_encode($results));
echo $str;
?>
and the result is:
[{"category":"CategoryA","name":"name1","description":"description1"},
{"category":"CategoryB","name":"name2","description":"description2"},
{"category":"CategoryA","name":"name3","description":"description3"},
{"category":"CategoryA","name":"name4","description":"description4"}]
As i'm an Android developer and my php knowledge is limited, how could i recreate my .php file in order to get the correct JSON format?
UPDATE: that works
foreach ($nameDescriptionPairs as $nameDescriptionPair) {
$result[$row['category']][] = array(
'name' => $nameDescriptionPair['name'],
'description' => $nameDescriptionPair['description']
);
}