convert stdclass object array to json correct - php

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.

Related

How to convert a PHP array into json string

I have a PHP array built with a while loop. I do successfully convert it to JSON string, however the output is not what I want and need some help to get it right:
My current code:
while(!$sql_query->EOF){
$data[] = array(
'id' => $id,
'name' => $name,
'title' => $title
);
$sql_query-> MoveNext(); }
echo json_encode($data);
The output I get with my code is this:
[
{
"id":"1",
"name":"Nick",
"title":"Office"
},
{
"id":"2",
"name":"Amy",
"title":"Home"
}
]
However, I need the outcome to be:
{
"data": [
[
"1",
"Nick",
"Office"
],
[
"2",
"Amy",
"Home"
]
]
}
I tired paying around with array_values() but no success so far.
Can somebody suggest the right approach here?
When building your array, don't add the keys to the values, this will allow the encoding to use array notation, then add the "data" key as part of the encode...
$data = [];
while(!$sql_query->EOF){
$data[] = [ $id, $name,$title];
$sql_query-> MoveNext();
}
echo json_encode(["data" => $data]);
If you do something like:
$result = (object)["data" => $data];
echo json_encode($data);
this will give you the output you require.
First of all you have to modify you array
$newData = [];
foreach($data as $item) {
$newData[] = array_values($item);
}
and then create new array
echo json_encode(["data"=>$newData])

Correctly forming API response

I am building a simple API response for my app with Symfony. This is the response I am trying to achieve:
"academy_programs": {
     "academy_program": {
“program_name”: “MySQL”,
“program_price”: 100,
}
 "academy_program": {
“program_name”: “PHP,
“program_price”: 500,
}
}
So far, my response looks like this:
"academy_programs": {
"program_name": [
"MySQL",
"PHP"
],
"program_price": [
100,
500
]
}
Here is the code I wrote.
$programsArray = array();
$priceArray = array();
foreach ($academy->getPrograms() as $program) {
$programsArray[] = $program->getProgramName();
}
foreach ($academy->getPrograms() as $price) {
$priceArray[] = $price->getProgramPrice();
}
$programs = new \stdClass();
$programs->program_name = $programsArray;
$programs->program_price = $priceArray;
I am missing another foreach that would loop through each entry.
You are getting the results in 2 different arrays. To achieve your results, you will have to add the name and the price inside a single array as shown below:
<?php
$programsArray = [];
$programsArray['academy_programs'] = [];
foreach ($academy->getPrograms() as $program) {
$programsArray['academy_programs'][] = [
'academy_program' => [
'program_name' => $program->getProgramName(),
'program_price' => $program->getProgramPrice()
]
];
}
print_r($programsArray);
echo json_encode($programsArray); // json representation
Update:
As #Jaquarh mentioned in the comments, you can make use of __toString() magic method to print contents $academy object whenever you print the object or use it in any string context.
Snippet:
<?php
class Academy{
/*
other code
*/
public function __toString(){
$programsArray = [];
$programsArray['academy_programs'] = [];
foreach ($this->getPrograms() as $program) {
$programsArray['academy_programs'][] = [
'academy_program' => [
'program_name' => $program->getProgramName(),
'program_price' => $program->getProgramPrice()
]
];
}
return json_encode($programsArray); // json representation
}
}
$academy = new Academy();
/*
all the other jazz
*/
echo $academy; // this would invoke the __toString() method and will give you the json representation as output.
Just need to create array like below and use json_encode as below
$academy_programs = [
$academy_program = [ 'program_name' => 'MySQL', 'program_price' => '100' ],
$academy_program = [ 'program_name' => 'PHP', 'program_price' => '500' ]
];
// echo "<pre>"; print_r($academy_programs);
echo json_encode( [ 'academy_programs' => $academy_programs ]);
Here you will get output as
{"academy_programs":[{"program_name":"MySQL","program_price":"100"},{"program_name":"PHP","program_price":"500"}]}

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);

Convert PHP array to JSON using multi dimentional arrays

I am trying to convert this php array to a json. This is my code:
$c = array();
$c = array(
$c['cronjobs'] = array(
'id'=>1189515,
'groupId'=>12379,
),
);
$json = json_encode($c);
echo $json;
This is the output I'd like to acieve:
{"cronjobs":[{"id":1186437,"groupId":12379]}
Though using the above code this is what I am getting
[{"id":1189515,"groupId":12379}]
The [{"cronjobs"part is not appearing.
I'm not sure what I'm doing wrong.
This should get the result that you want (just wrap an array around the id, groupId array):
<?php
$c = array();
$c['cronjobs'] = array(array(
'id'=>1189515,
'groupId'=>12379,
));
echo json_encode($c);
// result {"cronjobs":[{"id":1189515,"groupId":12379}]}
?>
This is how you need to format your array:
$c = array(); // declare the array
$c['cronjobs'] = array( // populate the array
'id'=>1189515,
'groupId'=>12379,
);
$json = json_encode($c); // json_encode it
echo $json;
There is no need for $c = array($c['cronjob']); (which was what you were doing).
I think this is what you're looking for:
$c = array('cronjobs' => array());
$c['cronjobs'][] = array('id' => 1189515, 'groupId' => 12379);
//$c['cronjobs'][] = array('id' => 1234, 'groupId' => 4321);
$json = json_encode($c);
echo $json;
Cronjobs needs to contain an array of cronjob objects/arrays
Could also be written using one statement, like this:
$c = array('cronjobs' => array(
array('id' => 1189515, 'groupId' => 12379),
array('id' => 1234, 'groupId' => 4321)
));
Your problem is that in PHP array is used to represent both JSON objects and JSON lists hence the confusion. Consider the following code:
$cronjob = array(
'id' => 1189515,
'groupId' => 12379
);
echo json_encode($cronjob);
// {"id":1189515,"groupID":12379"}
As you can see this represents a single object. So we'll create a list of objects:
$cronjobs = array($cronjob);
echo json_encode($cronjobs);
// [{"id":1189515,"groupID":12379"}]
This is now a list as expected. Now the parent object:
$c = array(
'cronjobs' => $cronjobs
);
echo json_encode($c);
// {"cronjobs":[{"id":1189515,"groupID":12379"}]}
In JSON there is a name: value pair system
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
if you want to achieve like {"cronjobs":[{"id":1186437,"groupId":12379]} then the array must be named like the following in PHP:
$c['cronjobs'] = array(
'id'=>1189515,
'groupId'=>12379,
);
$json = json_encode($c);
echo $json;

How to format array as key : value?

I have a array like this:
Array
(
[0] => Chat Show
[1] => Non-fiction
[2] => Inspirational
)
And i am trying to get this format:
"genres": [
{
"name": "Chat Show"
},
{
"name": "Non-fiction"
},
{
"name": "Inspirational"
}
]
but i get something like this:
genres": [
"Chat Show",
"Non-fiction",
"Inspirational"
]
This is what i am doing:
while($row = mysqli_fetch_array($Data))
{
$Genres = explode('/', filter_var(rtrim($row['genres'], '/'), FILTER_SANITIZE_URL));
}
and then this is part of a bigger array
"genres" => $Genres
print_r(
json_encode(["genres" => array_map(
function($v) { return ['name' => $v]; },
$Genres)]));
result
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]}
For example, here is your array in PHP
$var = array(
"Chat Show",
"Non-fiction" ,
"Inspirational"
);
Without a key "name". You should create a new array and push each element as an array to your new array.
$result = array();
foreach($var as $name)
{
$arr = array("name"=>$name);
array_push($result, $arr);
}
after that, encode your $result by using json_encode
$json = json_encode($result,true);
echo $json;
Here is my output by echo $json.
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
Try this:
$Genres=array("Chat Show","Non-fiction","Non-fiction");
$new["genres"]=array();
foreach($Genres as $key => $name){
$new["genres"][$key] = ['name' => $name];
}
echo json_encode($new);
Output
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Non-fiction"}]}
The json string you posted here is not a valid json OR is part of json.
So, you might already have genres in your javascript, and want to get the remaining thing, which is
[
{ "name": "Chat Show" },
{ "name": "Non-fiction" },
{ "name": "Inspirational" }
]
Your current PHP $Genres looks like this because you are exploding the string
$Genres = [ 'Chat Show', 'Non-fiction', 'Inspirational' ];
Apply this to change values of your current $Genres
array_walk($Genres, function(&$v){ $v = ['name'=>$v]; });
Use it in your javascript like,
"genres": <?php json_encode($Genres)?>
Try this:
$genres_new['name']=$Genres;
echo json_encode($genres_new);
Your problem is, that you have simple array of strings, but you want an associative multilevel array. This is an relative simple operation. First lets illustrate the problem with some code:
// That is what you have, an :
$Genres = [
"Chat Show",
"Non-fiction",
"Inspirational",
];
// or the same for php > 5.4:
$Genres = array(
"Chat Show",
"Non-fiction",
"Inspirational",
);
This will produce the following json string (echo json_encode($Genres);):
["Chat Show","Non-fiction","Inspirational"]
But if you want such an output:
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
You have to convert the strings into an array. You can do that with that (or a similar loop):
foreach($Genres as $key => $name){
$Genres[$key] = ['name' => $name];
}
After that your array look like this:
Array (
0 =>
array (
'name' => 'Chat Show',
),
1 =>
array (
'name' => 'Non-fiction',
),
2 =>
array (
'name' => 'Inspirational',
),
)
Putting things together you will get something like that:
<?php
// Do whatever is necessary to build your Genres array ...
$Genres = [
"Chat Show",
"Non-fiction",
"Inspirational",
];
// Convert the array into an array of arrays
foreach($Genres as $key => $name){
$Genres[$key] = ['name' => $name];
}
echo json_encode($Genres);
/**
Now you will get this output:
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
*/
// After that you can add it to the bigger array:
$biggerArray = [];
$biggerArray['genres'] = $Genres;
echo json_encode($biggerArray);
/**
Output:
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]}
*/

Categories