print foreach loop with json_encode in php - php

I am new to php. so it may be very basic but I don't know it. So, I want to output like this in php using json_encode().
"option": [
{
"poOptionGroup": "11",
"optGrpID": "11",
"optGrpName": "Choose Backing Material"
},
{
"optID": "40",
"optName": "Black (Plexiglass)",
"optPriceDiff": "0"
},
{
"optID": "41",
"optName": "Clear (Plexiglass)",
"optPriceDiff": "18"
},
{
"optID": "218",
"optName": "Neon Stand Off",
"optPriceDiff": "18"
},
{
"optID": "219",
"optName": "White Plastic",
"optPriceDiff": "18"
}
],
"option": [
{
"poOptionGroup": "13",
"optGrpID": "13",
"optGrpName": "Any notes you want to include with your order"
},
{
"optID": "174",
"optName": "NO Thanks",
"optPriceDiff": "0"
},
{
"optID": "175",
"optName": "YES OUTDOOR",
"optPriceDiff": "170"
}
],
"SPIN3": [
{
"poOptionGroup": "56",
"optGrpID": "56",
"optGrpName": "Upgrade to OUTDOOR"
},
{
"optID": "44",
"optName": "",
"optPriceDiff": "20.02"
}
]
for this I have two nested foreach loop. which is as below:
$product=array();
foreach($query as $q){
$product['optGrpID']= $q['optGrpID'];
$product['optGrpName'] = $q['optGrpName'];
$product['poOptionGroup'] = $q['poOptionGroup'];
$opt_id=$product['optGrpID'];
$string= sql("select optID, optName, optPriceDiff from options where optGroup='$opt_id' ");
foreach ($string as $k=>$s){
$product['options']['optID']=$s['optID'];
$product['options']['optName']=$s['optName'];
$product['options']['optPriceDiff']=$s['optPriceDiff'];
}
}
so how can I achieve this desired output? please help. any help will be appreciate.

I am right in the proces of writing a PHP JSON API so I came across similar problems in the past few days. While I can't / don't want to solve your particular question about the PHP code, here is the most important thing I learned that I didn't find in many documentations or tutorials:
Giving json_encode() an associative array produces an JSON object with {key: value, key: value, ...}. Giving it a non-associative array produces a JSON list with [value, value, value, ...]. The values in the latter version can off course be objects them self ({...}). This means to get the structure you want, you have to pass the following array to json_encode:
array(
"option" => array(
array(
"optId" => "40",
"optName": "Black (Plexiglass)",
"optPriceDiff": "0"
),
array(
"optId" => "40",
"optName": "Black (Plexiglass)",
"optPriceDiff": "0"
),
.......
),
"SPIN3" => array(
array(
"poOptionGroup" => "56",
"optGrpID" => "56",
"optGrpName" => "Upgrade to OUTDOOR"
),
array(
"optID" => "44",
"optName" => "",
"optPriceDiff" => "20.0"
)
)
);
As you can see, some of those arrays are associative arrays, some of them are non-associative arrays acting as a "simple list". Knowing this, it should be easy to modify your PHP code to produce an array like the above and pass it to json_encode(). Unless you force json_encode() to allways produce JSON objects with a flag, PHP handles the conversion to JSON objects and JSON lists as seen above.
For correct terminology: "list" refers to JSON arrays, whereas associative arrays are converted to JSON objects with string-value-links. See the JSON website for details.

Related

Convert Single Object into an Array containing that Object

I have a number of JSON files and when there is a single object in them, their datatype is inconsistent. I am trying to alter the files that contain one item so that the element I am referencing is always an array.
Here's an example of a 'good' JSON file:
{
"apiv2": {
"items": [{
"id": "00001",
"name": "ITEM 1"
}, {
"id": "00002",
"name": "ITEM 2"
}]
}
}
In PHP terms, $json->apiv2->items is always an array I can apply the same functions to.
Every so often I have a JSON file that contains one item:
{
"apiv2": {
"items": {
"id": "00003",
"name": "ITEM 3"
}
}
}
When I attempt to iterate through 'items' with the same functions, they fail as it is now an object instead of an array.
My goal is to alter the JSON data and rewrite the file so the single item files are consistent with the multiple item files:
{
"apiv2": {
"items": [{
"id": "00003",
"name": "ITEM 3"
}]
}
}
Maybe it's because it's Friday afternoon, but I can't seem to wrap my head around this one. I thought it would be as simple as:
$json->apiv2->items = (array) $json->apiv2->items;
But that just turns it into an array with two elements, "id" and "name", not one element with the object.
As I said in the comments
When you do
$json->apiv2->items = (array) $json->apiv2->items;
PHP will convert $items to an actual array [ "id" => "00003", "name" => "ITEM 3"]
Which will give you the results ['items' => [ "id" => "00003", "name" => "ITEM 3"]]
Instead of converting your object, you need to wrap it
$json->apiv2->items = [$json->apiv2->items];
More advanced: since sometimes items can be an array and sometimes not, you can make a function [1] to wrap them
function wrap($value)
{
if (is_null($value)) {
return [];
}
return is_array($value) ? $value : [$value];
}
$json->apiv2->items = wrap($json->apiv2->items);
POC : https://3v4l.org/7p9b0
[1] Stolen from Laravel helpers
Use json_decode() and access it like this:
$json = '{"apiv2":{"items": [{"id": "00001", "name": "ITEM 1" }, {"id": "00002", "name": "ITEM 2" }]}}';
print_r(json_decode($json, true)['apiv2']['items']);

Best Practice To Convert Regular Array To Associative Using An Attribute as a Key?

Let's say I have the following array
[
{
"id": "16",
"name": "dog",
},
{
"id": "17",
"name": "cat",
},
{
"id": "18",
"name": "mouse",
}
]
I want to use a specific attribute, id as the key for the array. I could do this:
$someArray = [
["id" => "16", "name" => "dog"],
["id" => "17", "name" => "cat"],
["id" => "18", "name" => "mouse"]
];
$newArray = [];
foreach ($someArray as $currItem)
{
$newArray[$currItem["id"]] = $currItem;
}
Then I would have this (the desired outcome)
{
"16": {
"id": "16",
"name": "dog"
},
"17": {
"id": "17",
"name": "cat"
},
"18": {
"id": "18",
"name": "mouse"
}
}
My question is: is there a better way to do this? Do I really have to loop through every item just to redefine my array ever so slightly?
I seem to have found a solution using information from Rizier123's comment and this thread: PHP Change Array Keys
As far as I can tell array_column is only going to give me an array of ids, so I need to use it with array_combine and array_values. Please don't be afraid to post if you have a better answer
$someArray = [
["id" => "16", "name" => "a"],
["id" => "17", "name" => "b"],
["id" => "18", "name" => "c"]
];
$newArray = array_combine(array_column($someArray, "id"), $someArray);
You beat me to the answer but I might contribute a little anyway...
I'm not sure where your original array is coming from, but if you are decoding JSON, then you can provide a second param to force objects to be converted to associative arrays
$contents = trim(file_get_contents("/home/jaith/foo/foo.json"));
$arr = json_decode($contents, TRUE); // note the second parameter
$v = array_combine(array_column($arr, "id"), $arr);
var_dump($v);
EDIT:
If you can tolerate your output array having objects, this might also work:
$contents = trim(file_get_contents("/home/jaith/foo/foo.json"));
$arr = json_decode($contents);
$v = array_combine(
array_column(
array_map(
function($item) { return (array)$item; },
$arr
),
"id"
),
$arr
);
var_dump($v);
Keep in mind though that performance could become a concern for very very large arrays. This is doing a lot of array munging.

Empty value in json array, key gets dropped

I am using the following code to display an external API in json format.
<?php
$result = file_get_contents('compress.zlib://https://URL', false, stream_context_create(array(
'http' => array(
'method' => 'GET'
)
))
);
echo($result);
?>
The result is like:
{
"product": [{
"product_name": "paper",
"product_no": "67",
"price": "7"
}, {
"product_name": "pencil",
"product_no": "69",
"price": "5"
}, etc]
}
However, if for example the value of the corresponding key "product_no" is empty, the key in that specific array is not visible anymore in json. I would like it to display "product_no":"", or something like that...

Return an Array instead of Object

I am fetching data from DB like this
$endResult = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
if (!isset($endResult[$row['car']])) {
$endResult[$row['car']]= (object) array(
'car' => $row['car'],
'carModel' => $row['carModel'],
'colors' => array()
);
}
$endResult[$row['car']] -> colors [] = (object) array(
'paintedOn' => $row['paintenOnDate'],
'paintedBy' => $row['paintedBy']
);
}
//return with slim.php
$response->body(json_encode($endResult));
and result I am getting
{"1":
{
"car": "1",
"carModel": "model-1",
"colors": [
{
"paintedOn": "2014-11-07",
"paintedBy": "5"
},{
"paintedOn": "2014-11-08",
"paintedBy": "6"
}]
},
"2":{
"car": "2",
"carModel": "model-2",
"colors": [
{
"paintedOn": "2014-11-09",
"paintedBy": "7"
},{
"paintedOn": "2014-11-10",
"paintedBy": "8"
}]
}
}//<--replace this with []
Even if $endResult is declared as Array I am getting {} brackets, how could I replace "Object" brackets with "Array" brackets?
UPDATE: I can't remove json_encode as the front-end (backbone) expecting collection
UPDATE 2: $endResult = array(); return [...]
but this $endResult[$row['car']]= (object) array(...) convert it to {...}
You can't achieve what you want because it would result in invalid JSON. According to json.org:
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
So you can only have values in an array. Because you are adding a name to the value, it must become an object.
If you really want your JSON to be wrapped in an array you need to remove the first-level names, in your example "1" and "2":
[
{
"car": "1",
"carModel": "model-1",
"colors": [
{
"paintedOn": "2014-11-07",
"paintedBy": "5"
},
{
"paintedOn": "2014-11-08",
"paintedBy": "6"
}
]
},
{
"car": "2",
"carModel": "model-2",
"colors": [
{
"paintedOn": "2014-11-09",
"paintedBy": "7"
},
{
"paintedOn": "2014-11-10",
"paintedBy": "8"
}
]
}
]
Remove the conversion to JSON. Also "declaration" in PHP doesn't matter. You can still assign different types in the course of your program.
I think the PHP function json_decode Should help you here. This turns the JSON format into an array.
use json_decode($data,true) for convert returned data in to array.
simply use array_values function:
$array = array_values($response);

Accessing JSON encoded PHP Array in jQuery

I have an PHP Array which is formatted in the following format :
$jsonArray = array(
"facebook" => array("user" => "8", "user_id" => "10", "user_post" => "6"),
"twitter" => array("user" => "8", "user_id" => "10", "user_post" => "6")
);
I've then done the following so I can access the array
echo "<script type='text/javascript'>window.MyArray = ".json_encode($jsonArray).";</script>";
And to access the array I tried the following
alert(window.MyArray['facebook'][0]['user']);
yet that's seemed to fail, any directions?
window.MyArray['facebook'][0]['user']
--------------------------^^^
Why do you need [0] here?
Use this:
window.MyArray['facebook']['user']
MyArray gives this:
{
"facebook": {
"user": "8",
"user_id": "10",
"user_post": "6"
},
"twitter": {
...
}
}
MyArray['facebook'] results in the following array:
{
"user": "8",
"user_id": "10",
"user_post": "6"
}
Therefore, MyArray['facebook']['user'] results in 8.
try this way:
alert(window.MyArray.facebook.user);
it will work
You are passing the json as a string, you need to convert it to an object. To do that you can use http://www.json.org/js.html

Categories