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"}]}
Related
Given the below code, how do I add an if statement inside obj so that the final PHP result does not display a field if it has a NULL value? For example, if id_info is NULL, then do not display "id":[id_info] in the actual PHP page? I couldn't find this info anywhere in the documentation.
<?php
$id_info = ($db->query("SomeSQL query")->fetch_assoc())['id'];
$name_info = ....;
//some more queries
$obj = (object) ["id" => strval($id_info),
"Name" => (object) [
"eng_name" => strval($name_info)
]];
echo json_encode($obj);
?>
As mentioned by knittl you could check if a specific value is null and not add it to your object.
If it is necessary though to dynamically create objects withouth the hustle of checking. You have to use array_filter or any other custom filtering function for that.
I wrote a custom filtering function that accepts a deeply nested array and returns it back filtered.
function arrayFilter($inputArr){
$output = null;
if (is_array($inputArr)){
foreach ($inputArr as $key=>$val){
if(!$inputArr[$key]) continue;
if (is_array($val)) {
$tmpArr = arrayFilter($val);
if($tmpArr) $output[$key] = array_filter($tmpArr);
}
else $output[$key] = $val;
}
} else {
$output[$key] = $val;
}
return $output;
}
So, lets say you have a deeply nested object similar to the one you provided
$obj = (object) [
"id" => null,
"Name" => (object) [
"eng_name" => strval('some name2'),
"de_name" => null,
"more" => (object) [
"fr_name" => strval('some name3'),
"ru_name" => null,
]
]
];
Below i convert the stdClass object you have to an array with json_encode and json_decode and if you pass it as a parameter into the function like:
$filtered = arrayFilter(json_decode(json_encode($obj), true));
Your output will be something like the following:
{
"Name":{
"eng_name":"some name2",
"more":{
"fr_name":"some name3"
}
}
}
Simply don't add it to the object in the first place:
$obj = [ "Name" => [ "eng_name" => strval($name_info) ] ];
if ($id_info != null) {
$obj["id"] = strval($id_info);
}
I use DomCrawler to grab some data, and I would like to know if I can get an array from a closure, here is my code :
$promises = $products
->each(function(Crawler $node) use ($client, $cookieJar) {
$href = $node->filter('a')->last()->attr('href');
return [
$href => $client->getAsync($this->config['url'] . $href, [
'cookies' => $cookieJar,
])
];
});
It will return me like :
$promises = [
['href_value' => Guzzle\Promise],
....
];
But I would like to have :
$promises = [
'href_value' => Guzzle\Promise,
....
];
How can I tranform the return statetement to have this result, something like this in my mind :
return ($href) => $client->getAsync($this->config['url'] . $href, [
'cookies' => $cookieJar,
]);
Transform your $promises to have flat array:
$flatPromises = [];
foreach ($promises as $promise) {
foreach ($promise as $key => $value) {
$flatPromises[$key] = $value;
}
}
My aim is to get an array of all userChecklistItems but the loop only returns one value. I think it has something to do with the category-array but I can't find a solution...
private $responseJson = [];
public function getArray($user) {
$responseJson['checklistItems'] = [
ChecklistItem::CATEGORY_DAY => [],
ChecklistItem::CATEGORY_WEEK => [],
ChecklistItem::CATEGORY_MONTH => [],
ChecklistItem::CATEGORY_ONE_HUNDRED_DAYS => []
];
$userChecklistItems = $user->getUserChecklistItems();
foreach($userChecklistItems as $userChecklistItem) {
$category = $userChecklistItem->getChecklistItem()->getCategory();
$responseJson['checklistItems'][$category] = [
'text' => $userChecklistItem->getChecklistItem()->getText(),
'isChecked' => $userChecklistItem->getIsChecked()
];
};
return $responseJson;
}
Ok, I got it - the newArray was missing
$userChecklistItems = $user->getUserChecklistItems();
$newArray = [];
foreach($userChecklistItems as $userChecklistItem) {
$category = $userChecklistItem->getChecklistItem()->getCategory();
$responseJson['checklistItems'][$category] = [
'text' => $userChecklistItem->getChecklistItem()->getText(),
'isChecked' => $userChecklistItem->getIsChecked()
];
$newArray[] = $responseJson;
};
return $newArray;
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.
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"}]}
*/