PHP push array into existing array - php

I have a php file I am using to create a JSON output. You can see my loop in the code below:
foreach($objQueueData->event as $event){
$output[] = array(
"eventID" => (int)$event->trainingEventID,
"eventTitle" => (string)$event->teTitle,
"eventDescription" => (string)$event->teDesc,
"eventSource" => (string)$event->teSource,
"eventType" => (string)$event->teType,
"eventMedium" => (string)$event->teMedium,
"eventRequestor" => (string)$event->creatorFirst . ' ' . $event->creatorLast,
"eventRequestorNTID" => (string)$event->creatorNTID,
"eventRequestDate" => (string)$event->teCreated,
"eventDirector" => (string)$event->teDirector,
"eventTeammateImpact" => (string)$event->teTeammateImpact,
"eventCustomerImpact" => (string)$event->teCustomerImpact,
"eventComplexity" => (string)$event->teComplexity,
"eventInitiativeID" => (int)$event->intID,
"eventNeededBy" => (string)$event->teNeededBy
);
$impactedRegions = array();
if(isset($event->regionalImpact->option)){
foreach ($event->regionalImpact->option as $region) {
$impactedRegions[] = $region->impact;
}
array_push($output, $impactedRegions);
}
}
// Set the content type to JSON for jquery to understand
header('Content-Type: text/json');
// Print the response to the page
print json_encode($output);
My issue is with the second array impactedRegions. This should be a sub array of output but it is not working as intended.
I am trying to have it be apart of the output array.
Here is what the current JSON output looks like:
[
{
"eventID": 25,
"eventTitle": "Monday",
"eventDescription": "Testing Monday",
"eventSource": "OE",
"eventType": "New Hire",
"eventMedium": "ILT",
"eventRequestor": "Carl",
"eventRequestorNTID": "ch123",
"eventRequestDate": "Nov 17 2014 4:58PM",
"eventDirector": "",
"eventTeammateImpact": "Medium",
"eventCustomerImpact": "High",
"eventComplexity": "Low",
"eventInitiativeID": 1069,
"eventNeededBy": "2014-11-18"
},
[
{
"0": "Americas"
}
],
Can anyone point me in the right direction?

foreach ($event->regionalImpact->option as $region) {
$output['regions'][] = $region->impact;
}

Try this
foreach($objQueueData->event as $key => $event){
$output[$key] = array(
"eventID" => (int)$event->trainingEventID,
"eventTitle" => (string)$event->teTitle,
"eventDescription" => (string)$event->teDesc,
"eventSource" => (string)$event->teSource,
"eventType" => (string)$event->teType,
"eventMedium" => (string)$event->teMedium,
"eventRequestor" => (string)$event->creatorFirst . ' ' . $event->creatorLast,
"eventRequestorNTID" => (string)$event->creatorNTID,
"eventRequestDate" => (string)$event->teCreated,
"eventDirector" => (string)$event->teDirector,
"eventTeammateImpact" => (string)$event->teTeammateImpact,
"eventCustomerImpact" => (string)$event->teCustomerImpact,
"eventComplexity" => (string)$event->teComplexity,
"eventInitiativeID" => (int)$event->intID,
"eventNeededBy" => (string)$event->teNeededBy
);
$impactedRegions = array();
if(isset($event->regionalImpact->option)){
foreach ($event->regionalImpact->option as $region) {
$impactedRegions[] = $region->impact;
}
}
$output[$key]['impactedRegions'] = $impactedRegions;
}
// Set the content type to JSON for jquery to understand
header('Content-Type: text/json');
// Print the response to the page
print json_encode($output);

I think the problem you are having is you are using array_push() with an associative array. I believe array_push is for pushing values to an indexed array.
Trying specifying the key by using $output['impactedRegions'] = $impactedRegions; instead.
$impactedRegions = array();
if(isset($event->regionalImpact->option)){
foreach ($event->regionalImpact->option as $region) {
$impactedRegions[] = $region->impact;
}
$output['impactedRegions'] = json_encode($impactedRegions);
}
Also, json_encode($impactedRegions) will encode the array so it's included as a json object in your original array.

Related

How to create nested tag in JSON

I have been fiddling with JSON nested tag, tried the basics now I want to go a little further, but it has been giving a little head ache to me. I have this public function below
public function returnResponse($code, $data){
header("content-type: application/json");
$result = json_encode(['response' => ['status' => $code, "message" => $data]]);
echo $result ; exit;
}
$order= $cust->getDeliveryDetail();
USING print_r($order);
Array
(
[0] => Array
(
[0] => Array
(
[order_id] => 4444
[menu] => two
[order_uniq] => 999oeo4
)
)
[1] => Array
(
[0] => Array
(
[pro_name] => Beans
[pro_sub] => Goods
[pro_type] => Open CA
)
[1] => Array
(
[pro_name] => Rice
[pro_sub] => Fiber
[pro_type] => Diverca
)
)
)
then attaching object with elements and value which references
$result ['order_id'] = $order[0][0]['order_id'];
$result ['menu'] = $order[0][0]['menu'];
$result ['order_uniq'] = $order[0][0]['order_uniq'];
$result ['pro_name'] = $order[0][0]['pro_name'];
$result ['pro_sub'] = $order[0][0]['pro_sub'];
$result ['pro_type'] = $order[0][0]['pro_type'];
$this->returnResponse(SUCCESS_RESPONSE, $result); //THIS IS THE ORIGINAL BEGINNING PUBLIC FUNCTION WE CREATED
to create this JSON nested tag below
{
"response": {
"status": 200,
"message": {
"order_id": "4444",
"menu": "two",
"order_uniq": "999oeo4",
"pro_name": "Beans",
"pro_sub": "Goods",
"pro_type": "Openca",
}
}
}
but I want to create a JSON nested tag like this below
{
"response": {
"status": 200,
"message": {
"order_id": "4444",
"menu": "two",
"order_uniq": "999oeo4",
"items": [
{
"pro_name": "Beans",
"pro_sub": "Goods",
"pro_type": "Openca",
}
{
"pro_name": "Rice",
"pro_sub": "Fiber",
"pro_type": "Diverca",
}
]
},
}
}
If it helps -- maybe not, the right way to do this in the beginning would be to create an OrderItems table/dictionary. Then store items in that table referrencing your Order table with "order_id". That way you could pull order_items as one array object, and convert that to json really simply.
Here since, you are getting "pro_name", "pro_sub" & "pro_type" as items, you would programmatically pull those out and create your own order_items array.
$order= $cust->getDeliveryDetail();
$order_id = $order[0][0]['order_id'];
$order_menu = $order[0][0]['menu'];
$order_uniq = $order[0][0]['order_uniq'];
$items = [];
foreach($order[1] as $order_item) {
$items[] = $order_item;
}
$result = [];
$result["order_id"] = $order_id;
$result["menu"] = $order_menu;
$result["order_uniq"] = $order_uniq;
$result["order_items"] = $items;
$this->returnResponse(SUCCESS_RESPONSE, $result);
Like this?
$result = array(
'order_id' = > $order[0][0]['order_id'],
'menu' => $order[0][0]['menu'],
'order_uniq' => $order[0][0]['order_uniq'],
'pro_name' => $order[0][0]['pro_name'],
'pro_sub' => $order[0][0]['pro_sub'],
'pro_type' => $order[0][0]['pro_type'],
'items' => array()
);
foreach($order[1] as $item) {
array_push(
$result['items'],
array(
'pro_name' => $item['pro_name'],
'pro_sub' => $item['pro_sub'],
'pro_type' => $item['pro_type'],
)
);
}

PHP variable gets last object in database instead of all objects

First off, sorry if the title is off...it's the best thing I could think of as to what issue I'm facing.
In my database, I have a list of apps. In PHP, I'm pulling their data from their key, and encoding that data into JSON to be printed out (I'm making an API).
However, only the last app gets printed out in JSON. What I need is a JSON array with ANY apps that have the same key so I can loop through them later, and print out their data.
My code:
$getApp = "SELECT * FROM tundra.apps WHERE app_key = '" . $api_key . "'";
$appData = $dbConnection->query($getApp);
if ($appData->num_rows > 0){ // Check if app_key exists
while($row = $appData->fetch_assoc()) { // While retrieving rows
$jsonApp = json_encode(array( // Encode the row data
"app_name" => $row['app_name'],
"app_theme" => array(
"primary_color" => $row['app_primary_color'],
"primary_color_dark" => $row['app_primary_dark_color'],
"accent_color" => $row['app_accent_color'],
),
"app_navigation" => $row['app_navigation'],
"author_info" => array(
"author_name" => $row['app_author_name'],
"author_bio" => $row['app_author_bio'],
"links" => array(
"website" => $row['app_author_website'],
"googleplus" => $row['app_author_gplus'],
"twitter" => $row['app_author_twitter'],
"dribble" => $row['app_author_dribble'],
"behance" => $row['app_author_behance'],
)
),
"app_status" => $row['app_status']
), JSON_UNESCAPED_SLASHES);
}
// Format and print JSON data
echo "<pre>" . prettyPrint($jsonApp) . "</pre>";
} else { // No key found, encode error
$jsonError = json_encode(
array(
array(
"error" => array(
"code" => "8",
"message" => "Invalid API key specified"
)
)
), JSON_UNESCAPED_SLASHES);
echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}
For the above, I tried echoing the JSON data in the while loop, but that (as expected) printed <pre>s for every row.
Here's the JSON output from the above code:
{
"app_name":"Andrew's Second App",
"app_theme":{
"primary_color":"#FFFFFF",
"primary_color_dark":"#E0E0E0",
"accent_color":"#E91E63"
},
"app_navigation":"0",
"author_info":{
"author_name":"Andrew Quebe",
"author_bio":"I'm a developer of stuff.",
"links":{
"website":"http://www.andrewquebe.com",
"googleplus":"https://plus.google.com/+AndrewQuebe",
"twitter":"https://twitter.com/andrew_quebe",
"dribble":"None",
"behance":"None"
}
},
"app_status":"1"
}
Note: the data is perfectly formatted, but I need the data to be in an array and I'm unsure as to how to do this.
The problem is, you're applying json_encode() function in each iteration of while() loop, plus you're overwriting $jsonApp in each iteration. And that's why you're getting that output.
The solution is, create an empty result array outside of while() loop. In each iteration of while() loop, push that array into the result array. And finally after coming out of the loop, apply json_encode() function on the result array and display it.
So your code should be like this:
// your code
if ($appData->num_rows > 0){ // Check if app_key exists
$resultArr = array();
while($row = $appData->fetch_assoc()) { // While retrieving rows
$resultArr[] = array( // Encode the row data
"app_name" => $row['app_name'],
"app_theme" => array(
"primary_color" => $row['app_primary_color'],
"primary_color_dark" => $row['app_primary_dark_color'],
"accent_color" => $row['app_accent_color'],
),
"app_navigation" => $row['app_navigation'],
"author_info" => array(
"author_name" => $row['app_author_name'],
"author_bio" => $row['app_author_bio'],
"links" => array(
"website" => $row['app_author_website'],
"googleplus" => $row['app_author_gplus'],
"twitter" => $row['app_author_twitter'],
"dribble" => $row['app_author_dribble'],
"behance" => $row['app_author_behance'],
)
),
"app_status" => $row['app_status']
);
}
$jsonApp = json_encode($resultArr, JSON_UNESCAPED_SLASHES);
// Format and print JSON data
echo "<pre>" . prettyPrint($jsonApp) . "</pre>";
} else { // No key found, encode error
$jsonError = json_encode(
array(
array(
"error" => array(
"code" => "8",
"message" => "Invalid API key specified"
)
)
), JSON_UNESCAPED_SLASHES);
echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}
In your while loop, you're constantly re-asigning values to $jsonApp. I would recommend adding the values more like this:
$getApp = "SELECT * FROM tundra.apps WHERE app_key = '" . $api_key . "'";
$appData = $dbConnection->query($getApp);
if ($appData->num_rows > 0){ // Check if app_key exists
for($i=0;$row = $appData->fetch_assoc();i++) { // While retrieving rows
$jsonApp[i] = array( // Encode the row data
"app_name" => $row['app_name'],
"app_theme" => array(
"primary_color" => $row['app_primary_color'],
"primary_color_dark" => $row['app_primary_dark_color'],
"accent_color" => $row['app_accent_color'],
),
"app_navigation" => $row['app_navigation'],
"author_info" => array(
"author_name" => $row['app_author_name'],
"author_bio" => $row['app_author_bio'],
"links" => array(
"website" => $row['app_author_website'],
"googleplus" => $row['app_author_gplus'],
"twitter" => $row['app_author_twitter'],
"dribble" => $row['app_author_dribble'],
"behance" => $row['app_author_behance'],
)
),
"app_status" => $row['app_status']
);
}
$json = json_encode($jsonApp,JSON_UNESCAPED_SLASHES);
// Format and print JSON data
echo "<pre>" . prettyPrint($json) . "</pre>";
} else { // No key found, encode error
$jsonError = json_encode(
array(
array(
"error" => array(
"code" => "8",
"message" => "Invalid API key specified"
)
)
), JSON_UNESCAPED_SLASHES);
echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}
This should show a JSON array, with each element in the array representing an individual app entry.
This is the format of JSON. You can not output different shapes. However, when decoding this JSON output, you can either decode objcet or array.
$object = json_decode($json);
$array = json_decode($json, true);
I believe it's because on line 6 of your example you're assigning the output of json_encode to the $jsonApp variable. It would be easier to use an array like so.
$jsonApp[] = array(
And then use json_encode at the end.
echo "<pre>" . prettyPrint(json_encode($jsonApp)) . "</pre>";

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"}]}
*/

adding array in PHP

First, im new in PHP so please bear with me.
I just want to add an array with the foreach loop but I can't.
if($size > 0)
{
$resultArray = array();
foreach($result as $hospital)
{
if($hospital)
{
$temp = array('result' => 'true',
'total' => $size,
'id' => $hospital['id'],
'name' => $hospital['name'],
'address' => $hospital['address'],
'telp' => $hospital['telp']);
$resultArray = array_merge_recursive($resultArray, $temp);
//$resultArray = array_splice($resultArray, $i, 0, $temp);
}
}
$this->response($resultArray, 200);
}
I tried to create a $temp array and merge it to the final result, and finally print that final result ($resultArray) to the response.
The array is successfully merged, but not in the way i want. This is the JSON result :
{"result":["true","true"],"total":[2,2],"id":["1","2"],"name":["test","keyword"],"address":["alamat test","alamat keyword"],"telp":["123456","789"]}
What i want is something like this :
-0 :{
result: "true"
total: 2
id: "1"
name: "test"
address: "alamat test"
telp: "123456"
}
-1 :{
result: "true"
total: 2
id: "2"
name: "test2"
address: "alamat tes 2t"
telp: "789"
}
So the response should be an array with 2 items, and each items has some items.
Please kindly help me, Thanks for your help.
It looks to me like you're trying to append an array, to an array, which can be done quite easily:
$resultArray = array();//outside the loop
//loop
$resultArray[] = array(
'result' => 'true',
'total' => $size,
'id' => $hospital['id'],
'name' => $hospital['name'],
'address' => $hospital['address'],
'telp' => $hospital['telp']
);
Job done. You could also use the array_push function, but that's a function. Functions equal overhead, and should, therefore be avoided (if it doesn't affect code readability). You use array_merge and array_merge_recursive if you want to combine arrays:
$foo = array(
array('bar' => 'zar')
);
$bar = array(
array('car' => 'far')
);
var_dump(
array_merge(
$foo,
$bar
)
);
The effect of array_merge here is comparable to:
foreach ($bar as $subArray)
$foo[] = $subArray;
Im not totally sure how you want your final array to be, but this will put it like $resultArray[0] = array( //temparray ) etc..:
if($size > 0){
$resultArray = array();
$i=0;
foreach($result as $hospital){
if($hospital){
$temp = array('result' => 'true',
'total' => $size,
'id' => $hospital['id'],
'name' => $hospital['name'],
'address' => $hospital['address'],
'telp' => $hospital['telp']);
$resultArray[$i][$temp];
$i++;
}
}
$this->response($resultArray, 200);
}
Replace this -
$resultArray = array_merge_recursive($resultArray, $temp);
With this -
$resultArray[] = $temp;

JSON array start with several Array

I'm trying to create JSON feed from one site which i want to decode on another. The problem is there seem to be to many array[0], so it is hard to loop through it and count how many objects there are.
How can i do this encode and decode without getting all these arrays, to make it easier to count the amount of objects and loop through it.
at the moment i'm encoding it like this:
$data = array();
foreach ($posts as $post) {
$r = str_replace("\n",'', shorten_txt($post->post_content, 500));
$n = str_replace("\r", '', $r);
$post_data = array(
'title' => get_the_title($post->ID),
'link' => get_permalink($post->ID),
'image' => catch_that_image(),
'content' => $n,
'time' => get_the_date( $d)." ". get_the_time( $d));
$data[] = (array('item' => $post_data));
}
echo json_encode($data);
This gives this output:
[
{
item: {
title: "Hello world!",
link: "http://URL/wordpress/?p=1",
image: "http://URL/wordpress/wp-content/uploads/2014/04/Digital-Board-2.png",
content: "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!",
time: "April 17, 2014 5:32 pm"
}
}
]
When i decode this i get this:
Array ( [0] => Array ( [item] => Array( [title] => Hello world! [link] => http://URL/wordpress/?p=1 [image] => http://URL/wordpress/wp-content/uploads/2014/04/Digital-Board-2.png [content] => Welcome to WordPress. This is your first post. Edit or delete it, then start blogging! Jeg elsker kage [time] => April 17, 2014 5:32 pm ) ) )
The decode code:
$json_string = 'http://95.85.11.40/wordpress/?page_id=20';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
print_r($obj);
If you don't want those array[0] bits, then don't create a 2D array:
$data[] = (array('item' => $post_data));
Should then be:
$data[] = $post_data;
Your current statement read as _add to array $data an array, with 1 key: "item", whereas my version just says: add to $data the value of $post_data.
loping oiver decoded data:
$data = json_decode(file_get_contents($jsonFile), true);
foreach ($data as $idx => $item)
{
echo 'This is item number ', $idx +1, PHP_EOL;
print_r($item);
}

Categories