Change response format of REST API - php

I'm working on my REST API responses with PHP.
Here is my backend that generates the responses:
$query = $this->db->query("SELECT some_params from some_table ");
$result = $query->result();
foreach($result as $row){
$obj[] = array(
'title' => $row['title'],
'price' => $row['price'],
);
}
print_r(json_encode($obj));
and with that I have the following response: an array of json objects
[
{
"title":"Marketing",
"price":"0"
},
{
"title":"SAP B1",
"price":"10"
}
]
What I would like to do is return a new object, something like this:
{
"apiVersion": "2.0",
"data": {
{
"title":"Marketing",
"price":"0"
},
{
"title":"SAP B1",
"price":"10"
}
}
}
Does anyone have any idea how I could implement this? thanks!

You can easily have a class or function to do that for you. Some thing like below should help,
// provided you are using php > 7 . otherwise parmas
// can become $data, $apiversion ( without typecasting )
function api_reponse(array $data, string $apiVersion)
{
return json_encode([
'apiVersion' => $apiVersion,
'data' => $data
])
}
You can then use,
$query = $this->db->query("SELECT some_params from some_table ");
$result = $query->result();
foreach($result as $row){
$obj[] = array(
'title' => $row['title'],
'price' => $row['price'],
);
}
print_r( api_response($obj, '2.0') );

Related

convert stdclass object array to json correct

Sorry for my English, I need help I want to convert a query which will return this.
{"ids":"1","user":"aki","last":"terris","job":"programmer"}{"ids":"1","user":"ako","last":"acros","job":"Artist"}
Change it to
{
"users": [
{
"user": "aki",
"last": "terris",
"job": "programmer"
},
{
"user": "ako",
"last": "acros",
"job": "Artist"
}
]
}
I tried with while, foreach but none gives me a valid format, some help
consult:
$sql = $db->query("SELECT * FROM user_s WHERE ids = '1' ");
$set_users = $sql;
Ex :
$entity = array();
while ($get_users = $set_users->fetch_object()) {
$entity = array(
'id' => $get_users->id,
'user' => $get_users->user
);
}
$fsi = array(
'users' => $entity,
);
echo $fsi;
Try this:
$results = new \stdClass;
$results->users = [];
while ($get_users = $set_users->fetch_object()) {
$entity = array(
'user' => $get_users->user,
'last' => $get_users->last,
'job' => $get_users->job,
);
$results->users[] = $entity;
}
echo json_encode($results);
You can use fetch_all with the MYSQLI_ASSOC option, to get data immediately in the desired format, i.e. as an associative array which will render JSON object notation when converted with json_encode:
$fsi = [ 'users' => $set_users->fetch_all(MYSQLI_ASSOC) ];
echo json_encode($fsi);
Make sure to use an SQL query that only selects the fields that you want to end up in the JSON.

Mapping SQL query results to JSON in PHP

I'm running into some issues getting the correct JSON output from my SQL query. Essentially what I'm struggling with is getting an array of options objects as opposed to singular option objects.
$query = 'SELECT matchup.matchupID, matchup_option.player_name, matchup_option.player_id FROM matchup
INNER JOIN matchup_option
ON matchup_option.matchupID= matchup.matchupID;';
$attachments = $db->query($query);
$data = array();
while ($attachment = $db->fetch_array($attachments)){
$data[] = array (
'id' => $attachment['matchupID'],
'options' => array(
array (
"name" => $attachment['player_name'],
"playerid" => $attachment['player_id']
)
)
);
//VAR_DUMP($attachment);
}
$data = array("matchup"=>$data);
print json_encode($data);
Gives me this output:
{
"matchup":[
{
"id":"111222",
"options":[
{
"name":"111",
"playerid":"111"
}
]
},
{
"id":"111222",
"options":[
{
"name":"222",
"playerid":"222"
}
]
}
]
}
And here's what I'm trying to get to:
{
"matchup":[
{
"id":"111222",
"options":[
{
"name":"111",
"playerid":"111"
},
{
"name":"222",
"playerid":"222"
}
]
}
]
}
I'd like to follow best practices as well as structure this appropriately, if there's a better way to go about this, please let me know!
You need to store $attachment['matchupID'] as an array key of $data:
$data = array();
while ($attachment = $db->fetch_array($attachments)){
if (!isset($data[$attachment['matchupID']])) {
$data[$attachment['matchupID']] = array (
'id' => $attachment['matchupID'],
'options' => array()
);
}
$data[$attachment['matchupID']]['options'][] = array (
"name" => $attachment['player_name'],
"playerid" => $attachment['player_id']
);
}
// use `array_values` to reindex `$data`
$data = array("matchup" => array_values($data));
print json_encode($data);

Magento select query not looping properly using a foreach loop

I have written following code:
try {
$json = array('success' => true);
$read = $this->read;
$readresult = $read->fetchAll("SELECT * FROM brand");
foreach($readresult as $r) {
$json['brands'][] = array(
'id' => $r['brand_id'],
'name' => $r['name'],
'description' => $r['description'],
);
}
return $json;
} catch (Exception $e) {
$message = $e->getMessage();
echo json_encode(array("status" => "500", "error" => $message));
}
In this code I am trying to display all the brand records from the database table.
But the problem is when I am trying to output the result the it is only displaying one record.
Can anyone please check what is the problem.
The output of the code above is:
{
"success":true,
"products":[
{
"id":"4",
"name":"Test",
"href":"http:\/\/localhost:8‌​1\/magento\/index.php\/catalog\/product\/view\/id\/4\/",
"thumb":"http:\/\/localho‌​st:81\/magento\/media\/catalog\/product\/cache\/0\/thumbnail\/9df78eab33525d08d6e‌​5fb8d27136e95\/images\/catalog\/product\/placeholder\/thumbnail.jpg",
"pirce":"$11‌​1,111.00"
}
]}
try like this,
$json['brands'] = array();
foreach($readresult as $r) {
$brand = array(
'id' => $r['brand_id'],
'name' => $r['name'],
'description' => $r['description'],
);
array_push($json['brands'],$brand);
}

I am getting json data in a different format in codeigniter. Why?

I am trying to make and return json data using codeigniter. I want to receive that data in this format
[
{
'title': 'this is title',
'desc': 'THis is desc'
},
{
'title': 'this is title',
'desc': 'THis is desc'
}
]
But I am receiving it this way
[[{"title":"this is title","desc":"this is desc"}],[{"title":"this is title","description":"this is desc"}]]
how can I change this format to above one?
here is my code
public function v1 () {
$this->load->model('model_jokes');
$jokes = $this->model_jokes->readJokes();
$arr = array();
foreach ($jokes as $joke) {
$arr[] = array(
array(
'title' => $joke->title,
'description' => $joke->joke
)
);
}
echo json_encode($arr);
}
Make the assignment inside foreach as
$arr[] = array(
'title' => $joke->title,
'description' => $joke->joke
);
Otherwise you will get a multi-dimensional array for each $joke.
You are adding array of array element each time in a loop. Instead just add single array.
public function v1 () {
$this->load->model('model_jokes');
$jokes = $this->model_jokes->readJokes();
$arr = array();
foreach ($jokes as $joke) {
$arr[] = array(
'title' => $joke->title,
'description' => $joke->joke
);
}
echo json_encode($arr);
}
Try :
echo '<pre>'.json_encode($arr).'</pre>';

Displaying multiple rows in PHP array

I have a script I wrote to return records for cases out of the database. I am returning one record for my mysql query when there are actually two records. This is what I am returning:
{ "cases": [ {"name":"Test Case for App","number":"3846"}] }
I should see:
{ "cases": [ {"name":"Test Case for App","number": "2903"}, {"name":"Test Case 2","number": "2856"} ] }
Here is my source:
$sql = "select * from cases as c join contacts_cases as conc on c.id = conc.case_id where conc.contact_id = '1b360507'";
$query = mysql_query($sql);
// If we find a match, create an array of data, json_encode it and echo it out
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_assoc($query);
$response = array(
'name' => $row['name'],
'number' => $row['case_number']
);
echo '{ "cases": [ ', json_encode($response), "] }";
If you are expecting more than one result you should try
if (mysql_num_rows($query) > 0)
{
$responses = array();
while($row = mysql_fetch_assoc($query)) {
$responses[] = array(
'name' => $row['name'],
'number' => $row['case_number']
);
}
echo '{"cases": ' . json_encode($responses) . '}';
}
You need to loop through all the rows, you're just getting one.
Also, don't try to build the JSON yourself. Make the array how you want then json_encode the entire thing.
$cases = array();
while ($row = mysql_fetch_assoc($query)) {
$cases[] = array(
'name' => $row['name'],
'number' => $row['case_number']
);
}
echo json_encode(array('cases' => $cases));

Categories