json encode missing the comma? - php

I'm trying to get the correct json output after using php nested array and somehow when I use the json_encode it misses the commas between each key value pair and array of item.
$don_info_arr = array();
$don_info_arr['don_info']= array();
$st_contacts_arr = array();
$st_contacts_arr['st_contacts']= array();
$don_contact_arr = array();
$don_contact_arr['don_contact']= array();
$don_contact_item =array(
'first_name' => $donor->first_name,
'last_name' => $donor->last_name
);
//correspondence_contact
$correspondence_contact_arr = array();
$correspondence_contact_arr['correspondence_contact']= array();
$correspondence_contact_item =array(
'first_name' => $donor->first_name_c,
'last_name' => $donor->last_name_c
);
$submission = array(
"don_info" => array (
"st_contacts" => array (
"don_contact" => $don_contact_item,
"correspondence_contact" =>$correspondence_contact_item)
)));
echo json_encode($submission);
getting this result now.
{
"don_info": {
"st_contacts": {
"don_contact": {
"first_name": "Test1"
"last_name": "Test1"
}
"correspondence_contact": {
"first_name": "ABC"
"last_name": "ACDD"
}
}
}
What I want:
{
"don_info":{
"st_contacts":{
"don_contact":{
"first_name":"Test1",
"last_name":"Test2"
},
"correspondence_contact":{
"first_name":"ABC",
"last_name":"ACDD"
}
}
}

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 JSON Encoding within foreach loop

I'm trying to generate the following JSON data:
[
{
"ID": "A1000",
"name": "John Simpson",
"serialID": "S41234",
"tagID": "ABC6456"
},
{
"ID": "B2000",
"name": "Sally Smith",
"serialID": "B5134536",
"tagID": "KJJ451345"
},
{
"ID": "A9854",
"name": "Henry Jones",
"serialID": "KY4239582309",
"tagID": "HYG452435"
}
]
from within a PHP foreach loop which looks like this:
foreach($records as $record) {
$ID = $record->getField('propertyID');
$name = $record->getField('assignedName');
$serialID = $record->getField('serial');
$tagID = $record->getField('tag');
}
I've tried using:
$arr = array('ID' => $ID, 'name' => $name, 'serialID' => $serialID, 'tagID' => $tagID);
which works for each record within the loop, but can't work out the syntax to join them together into a single JSON data string?
Problem:- Your are over-writing your $arr variable each-time inside foreach() loop.That cause the issue.
Solution:- Instead of over-writing, assign values to array like below:-
$arr = []; //create empty array
foreach($records as $record) {
$arr[] = array(
'ID' => $record->getField('propertyID');
'name' => $record->getField('assignedName');
'serialID' => $record->getField('serial');
'tagID' => $record->getField('tag')
);//assign each sub-array to the newly created array
}
echo json_encode($arr);
Add records to some kind of aggregation array and then json_encode it:
$items = [];
foreach($records as $record) {
$items[] = [
'ID' => $record->getField('propertyID'),
'name' = $record->getField('assignedName'),
'serialID' => $record->getField('serial'),
'tagID' => $record->getField('tag'),
];
}
echo json_encode($items);
Try this:
$data= array();
foreach($records as $record) {
$data[] = array(
'ID' => $record->getField('propertyID');
'name' => $record->getField('assignedName');
'serialID' => $record->getField('serial');
'tagID' => $record->getField('tag')
);
}
echo json_encode($data);
Explanation: Make an array, put all the values on one of their numerical index with in the loop, json_enccode() it.
<?php
$ArrayName = array();
foreach($records as $record) {
$ID = $record->getField('propertyID');
$name = $record->getField('assignedName');
$serialID = $record->getField('serial');
$tagID = $record->getField('tag');
$ArrayName[] = array('ID' => $ID, 'name' => $name, 'serialID' => $serialID, 'tagID' => $tagID); //assign each sub-array to the newly created array
}
echo json_encode($ArrayName);
?
> Blockquote
You could use something like array_map() for this:
$result = array_map(function ($record) {
return [
'ID' => $record->getField('propertyID'),
'name' => $record->getField('assignedName'),
'serialID' => $record->getField('serial'),
'tagID' => $record->getField('tag'),
];
}, $records);
echo json_encode($result);
this code will help you:
<?php
$resultArray = array();
foreach($records as $record)
{
$newResultArrayItem = array();
$newResultArrayItem['ID'] = $record->getField('propertyID');
$newResultArrayItem['name'] = $record->getField('assignedName');
$newResultArrayItem['serialID'] = $record->getField('serial');
$newResultArrayItem['tagID'] = $record->getField('tag');
$resultArray[] = $newResultArrayItem;
}
$encodedArray = json_encode($ArrayName);
echo $encodedArray;
?>

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

Prepend key value to array - PHP

I have the below code in a for..loop is there a way I can add values to the beginning of the array?
$data = array();
$initial = strtotime('11:00:00');
for (; $initial < strtotime("23:00:59"); $initial = strtotime("+15 minutes", $initial)) {
if ($initial > strtotime("+45 minutes", time())) {
$row['value'] = date('Hi', $initial);
$row['label'] = date('H:i', $initial);
$data['data'][] = $row;
}
}
I want to add the below values to the top of the array. I have tried using array_unshift but I don't think it supports key-value pairs.
if(!isBetween('22:00', '09:59', date('H:i'))) {
$row['value'] = "asap";
$row['label'] = "ASAP";
}
My array output
{
"data": [
{
"value": "1145",
"label": "11:45"
}
]
}
I want to get this
{
"data": [
{
"value": "asap",
"label": "ASAP"
},{
"value": "1145",
"label": "11:45"
},
]
}
Un-shift should work if you pass the arguments correctly:
array_unshift($data["data"], $prepend);
Alternatively, you could use array_merge, like this:
$data["data"] = array_merge(array($prepend), $data["data"]);
With the following example data:
$data = [
"data" => [
[
"value" => "1145",
"label" => "11:45"
]
]
];
$prepend = [
"value" => "asap",
"label" => "ASAP"
];
$data["data"] = array_merge(array($prepend), $data["data"]);
print_r($data);
You would get this output (with both solutions):
Array (
[data] => Array (
[0] => Array (
[value] => asap
[label] => ASAP
)
[1] => Array (
[value] => 1145
[label] => 11:45
)
)
)
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
function array_unshift_assoc(&$arr, $key, $val) {
$arr = array_reverse($arr, true);
$arr[$key] = $val;
return array_reverse($arr, true);
}
Source: http://php.net/manual/en/function.array-unshift.php

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