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...
Related
I am trying to adhere to an integration requirement of having multiple items with the same key names, including its meta data into a main array to properly json_encode.
I have tried splitting out and joining arrays, array_push. The only workable solution I have is to manually build this part of the json package. Any help would be greatly appreciated.
Here is a sample of what I am struggling with:
$message_pack["Header"]["Sequence"] = 'TEST1';
$message_pack["Header"]["TC"] = "1";
$message_pack["ItemDetail"]["ItemName"] = "Item1";
$message_pack["ItemDetail"]["ItemCode"] = "123";
$message_pack["ItemDetail"]["Itemname"] = "Item2";
$message_pack["ItemDetail"]["ItemCode"] = "234";
$json_msg = json_encode($message_pack);
This will obviously only take the last value passed to the matching key name.
I need to adhere to this json format:
{
"Header": {
"Sequence": "TEST1",
"TC": "1",
},
"ItemDetail": [{
"ItemName": "Item1",
"ItemCode": "123" }
{ "ItemName": "Item2",
"ItemCode": "234" }]
}
You need to make "ItemDetail" an array, else you'll overwrite $message_pack["ItemDetail"]["Itemname"] and $message_pack["ItemDetail"]["ItemCode"]:
<?php
$message_pack["Header"]["Sequence"] = 'TEST1';
$message_pack["Header"]["TC"] = "1";
$message_pack["ItemDetail"][] = ["ItemName" => "Item1", 'ItemCode' => 123];
$message_pack["ItemDetail"][] = ["ItemName" => "Item2", 'ItemCode' => 234];
$json_msg = json_encode($message_pack, JSON_PRETTY_PRINT);
echo ($json_msg);
will output:
{
"Header": {
"Sequence": "TEST1",
"TC": "1"
},
"ItemDetail": [
{
"ItemName": "Item1",
"ItemCode": 123
},
{
"ItemName": "Item2",
"ItemCode": 234
}
]
}
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.
We are working with an API that brings back JSON in this format:
[
{
"Id": "d7526186-361c-e611-80da-00155df41a0a",
"LogicalName": "contact",
"Attributes": [
{
"Key": "customertypecode",
"Value": {
"Value": 1
}
},
{
"Key": "merged",
"Value": false
},
{
"Key": "territorycode",
"Value": {
"Value": 1
}
}
],
"EntityState": null,
"FormattedValues": [
{
"Key": "customertypecode",
"Value": "Default Value"
},
{
"Key": "address2_addresstypecode",
"Value": "Default Value"
},
{
"Key": "merged",
"Value": "No"
},
{
I am currently using foreach to organise this into a new, cleaner array - but the code base is getting rather large.
What would be the cleanest way of getting specific values based on specifying a key name?
Thanks so much for your help.
First using json_decode to convert to an array, then you can access it in any way you would a normal multi dimensional array... e.g.
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
from http://php.net/manual/en/language.types.array.php
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
I've got a request to present the data in the following format as a JSON feed:
{
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
However in my PHP code, I think I need to have a key itterator - but I end up with this format:
{
"0": {
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
"1": {
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
}
Any ideas on how to build the first data set with out having the index iterator?
simple create an array of objects, no need for the key (notice the [ ] surrounding your list)
json.txt
[{
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}]
example.php
<?php
$data = json_decode(file_get_contents('./json.txt'));
?>
It can be built like this:
$arr = array(
array(
'id' => 123,
'info' => array(
'code' => 'ZGE',
'description' => 'test1',
'type' => 'AVL'
)
),
array(
'id' => 456,
'info' => array(
'code' => 'ZDN',
'description' => 'test2',
'type' => 'CLR'
)
)
);
echo json_encode($arr);
Outputs
[
{
"id": 123,
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL"
}
},
{
"id": 456,
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR"
}
}
]
the JSON format you've specified in the first example (ie the requested format) is not valid JSON.
A valid JSON string must evaluate to a single Javascript object; the example you've given evaluates to two Javascript objects, separated by a comma. In order to make it valid, you would need to either enclose the whole thing in square brackets, to turn it into a JS array or enclose it in curly braces, and give each of the two objects a key.
The PHP code you've written is doing the second of these two options. It is therefore generating valid JSON code, about as close to the original request as could be expected while still being valid.
It would help if you'd shown us the PHP code that you've used to do this; without that, I can't really give you advice on how to improve it, but if you want to switch to the square bracket notation, all you need is to put your PHP objects into an unkeyed array, and json_encode() should do it all for you; you shouldn't need to use a keyed array or an iterator for that.
The only reason json_encode should produce the output you're seeing is adding another named key to the array that you're passing to json_encode, by default it should work as you want:
$json = '[
{
"id": "123",
"recall_info": {
"code":"ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "123",
"recall_info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
]';
$php = array(
(object) array(
'id' => '123',
'recall_info' => (object) array(
'code' => 'ZGE',
'description' => 'test1',
'type' => 'AVL',
'date' => '09/08/2012'
)
),
(object) array(
'id' => '123',
'recall_info' => (object) array(
'code' => 'ZGE',
'description' => 'test2',
'type' => 'CLR',
'date' => '16/02/2012'
)
)
);
var_dump(json_encode($php));