Decoding a JSON object and echo a specific value? - php

I have a PHP page where I reference a JSON object that looks like this:
{
"body": {
"zip": "02110",
"stores": [
{
"storeEmail": "email#email.com",
"storeName": "Name",
"city": "City",
"Availability": {
"123": {
"Quote": "daily",
"Display": "available",
}
},
},
Each JSON object contains multiple "stores", above is one example.
I can currently echo the store name by using this:
echo "<br>".$phpArray->body->stores{0}->storeName;
How do I echo the value "123" from the sample JSON? I would also like to echo the quote as a separate variable. The value "123" will change for different searches. Any help would be greatly appreciated!

$phpArray = json_decode($json, true);
foreach($phpArray['body']['stores'] as $store) {
echo $store['storeName'];
foreach{$store['Availabilty'] as $avail => $info) {
echo $avail; // 123
echo $info['Quote'];
}
}

$b = json_decode($a);
var_dump(key($b->body->stores{0}->Availability));
var_dump(reset($b->body->stores{0}->Availability)->Quote);
or a loop for stores
foreach($b->body->stores as $store) {
var_dump(key($store->Availability));
var_dump(reset($store->Availability)->Quote);
}

Related

Printing nested associative array in PHP

I'm using this code $json_output = (json_decode($json, true)); to transform from JSON to an associative array in PHP.
The resulting array looks too compĺex to me, I need to print only some keys and values but they are nested and so far I haven't been able to do it, the examples I had follow for printing are too basic for this.
This is part of my JSON:
{
"project": {
"company": "Company Name SA de CV",
"name": "Project Name",
"files": [
{
"project-id": "666666",
"filenameOnDisk": "HH-ORG-CMD-GUI-File.docx",
"uploaded-date": "2018-01-29T21:20:56Z",
"private": "0",
"version-id": "3939061",
"status": "active",
"tags": [
{
"name": "OPD",
"id": "25047",
"color": "#9e6957"
}
],
"id": "3796128",
"last-changed-on": "2018-01-29T21:21:46Z",
"versions": [],
"uploaded-by-user-first-name": "Someone",
"uploaded-by-user-last-name": "Anything",
"name": "HH-ORG-CMD-GUI-GUIA_RAPIDA_PARA_CREAR_PROCESOS",
"size": "262747",
"category-name": "Instructivos"
},
{
"project-id": "666",
etc...,
},
When parsed looks like
How do I print (lets say) filenameOnDisk and id keys of the Files array.
I don't know how to get to that nested array.
echo $json_output['project']['files'][0]['project-id'];
echo $json_output['project']['files'][0]['filenameOnDisk'];
echo $json_output['project']['files'][0]['version-id'];
Or you could put it in a foreach loop using an array of values you want (as long as they're all in the 'files' array). Eg.
$wantedValues = array("project-id","filenameOnDisk","version-id");
foreach ($wantedValues as $value) {
echo $json_output['project']['files'][0][$value];
}
I Just needed to add a couple of lines at the code provided by #SeeSamRun in order to get the full "Files" array.
$filesArray = $json_output['project']['files'];
$filesSize = count($filesArray);
$wantedValues = array("project-id","filenameOnDisk","version-id");
for ($i=0; $i < $filesSize; $i++) {
foreach ($wantedValues as $value) {
echo $json_output['project']['files'][$i][$value];
}
}

How to decode this json with foreach

This is the JSON
{
"circuit_list": [
{
"_id": "58c0f378a986f808cdaf94cf",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
},
{
"_id": "58c0f378a986f808cdaf94d0",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
}
}
I already try with this code
$json = json_decode($url, true);
foreach($json as $value)
{
$_id = $value->_id;
}
it didn't work. Please help, I need to get the value to show them on the view. Did I do this wrong? this json is difficult because i didn't understand the structure.
I usually decode json with format
[{"id":"1","name":"faisal"}]
like this and with my foreach it's working.
If the second parameter of json_decode is true, the function will return an array instead of an object. Also, you would need to loop over the circuit_list property of the object.
$json = json_decode($url); // <- remove the parameter
foreach($json->circuit_list as $value) // <- loop over circuit_list
{
$_id = $value->_id;
}
<?php
$json = json_decode($url,true);
foreach($json['circuit_list'] as $value)
{
$id = $value['_id'];
}
?>

PHP - object array into json

array of $setting['accountType'] :
$setting['accountType']['all'] = 'ALL';
$setting['accountType']['A1'] = 'VIP1';
$setting['accountType']['A2'] = 'VIP2';
PHP code to generate the object:
$object = new stdClass();
$myArray = array();
foreach ($setting['accountType'] as $key => $val)
{
$object->id = $key;
$object->desc = $val;
$myArray[] = $object;
}
$accountType = $myArray;
PHP code to format object into json:
json_encode(['accountType'=> [(object)$accountType]));
However, i get the output as below :
"accountType": [{
"0": {
"id": "A2",
"desc": "VIP"
},
"1": {
"id": "A2",
"desc": "VIP"
},
"2": {
"id": "A2",
"desc": "VIP"
}
}]
Problem 1: why $accountType only keep the last object when I loop through?
Problem 2: without the array key of $accountType [solved by using array_values($accountType)]
This is something that I am trying to achieve:
"accountType": [{
"id": "all",
"desc": "All "
}, {
"id": "A1",
"desc": "Normal"
}, {
"id": "A2",
"desc": "VIP"
}]
How to get the output as above?
You should use
json_encode(['accountType'=> $accountType]);
instead of
json_encode(['accountType'=> [(object)$accountType]]);
In your code you are putting $accountType inside another array that is why you are getting that result
Here is a Demo and Explanation
Edit: The entire code
$setting['accountType']['all'] = 'ALL';
$setting['accountType']['A1'] = 'VIP1';
$setting['accountType']['A2'] = 'VIP2';
$myArray = array();
foreach ($setting['accountType'] as $key => $val)
{
$object = new stdClass(); // Note: $object should be created inside the loop
$object->id = $key;
$object->desc = $val;
$myArray[] = $object;
}
$accountType = $myArray;
echo json_encode(['accountType'=> $accountType]);
And Here is the Revised Demo
Try this,
echo json_encode(array_values($your_array));
Let me know if its working
This is exactly the same thing, no?
The numerotation is displayed because you need it to access to the specific json object.
You have an array and you can access to each element by its key.

json object is bahaving wrongly

I am test-running a web application
where in json is required. I have the following json
structure:
{
"Articles": [
{
"Article": {
"ID": 111,
"title": "Idiot",
"author": "Moron",
"pubDate": "11/2/14",
"summary": "bla bla bla"
},
"Article": {
"ID": 222,
"title": "wisdom",
"author": "wise one",
"pubDate": "11/2/15",
"summary": "ha ha ha"
}
}
]
}
I then decided to check if a matching ID exits before adding
any record. To this effect, I wrote a method, encased it within
a JSon class as follows:
public function ID_Exists($ID){
$file = file_get_contents($this->FileName, true);
$data = json_decode($file, false); //get json in array string format
foreach($data as $child){
foreach($child as $item){
if($item->ID == $ID){
echo 'Exists';
}else{
echo 'Non Existent';
}
}
}
}
I test-ran it like:
$Obj = new JSon('file.json'); //knows what to do
if($Obj->ID_Exists(111)){
//ok ! no problem
}else{
////no problem
}
Here's the output I got:
Undefined property: stdClass::$ID in
C:\Server\wamp\www\Oweb\libs\dmanager.php on line 635
What am I doing wrong? I don't want to use the array
format of json_decode().
Your JSON structure is impossible. Articles is an array which contains a single object which contains the key Article twice - this cannot work.
Your structure needs to be:
{
"Articles": [
{
"ID": 111,
...
},
{
"ID": 222,
...
}
]
}
Which you can traverse using:
$data = json_decode($json);
foreach ($data->Articles as $article) {
if ($article->ID == ..) ..
}

handling nested json in looping

json after json_encoded
{
"data":[
{
"name":"JIN",
"id":"100007934492797"
},
{
"name":"aris",
"id":"100008128873664"
},
{
"name":"Madm",
"id":"34234234"
}
],
"paging":{
"next":"https://graph.facebook.com/v1.0/1380314981/friends?limit=5000&offset=5000&__after_id=enc_AeyRMdHJrW0kW9vIZ41uFPXMPgE-VwRaHtQJz2JWyVc0hMl9eOG10C6JWjoCO8O2E4m24EPr28gIt9mxQR8oIQmN"
}
}
I want to store the name and ID of my json in db. But when I use for loop there's a problem with the offset, I suspect it's the last part of the json. How to remove the paging part? I tried
foreach($friends as friend){
echo friend[0]->name;
}
First, your original code would never work:
foreach($friends as friend){
echo friend[0]->name;
}
Those references to friend should have $ in front of them making them $friend. Then to solve your larger issue, just use a nested foreach loop:
$json = <<<EOT
{
"data": [
{
"name": "JIN",
"id": "100007934492797"
},
{
"name": "aris",
"id": "100008128873664"
},
{
"name": "Madm",
"id": "34234234"
}
],
"paging": {
"next": "https://graph.facebook.com/v1.0/1380314981/friends?limit=5000&offset=5000&__after_id=enc_AeyRMdHJrW0kW9vIZ41uFPXMPgE-VwRaHtQJz2JWyVc0hMl9eOG10C6JWjoCO8O2E4m24EPr28gIt9mxQR8oIQmN"
}
}
EOT;
$friends = json_decode($json);
foreach($friends as $friend_data){
foreach($friend_data as $friend){
echo $friend->name . '<br />';
}
}
And the output of this would be:
JIN
aris
Madm
Additionally, if working with arrays makes more sense for you, you can always set json_decode to return an array by setting the second parameter to true. Here is refactored code as an example:
$friends = json_decode($json, true);
foreach($friends as $friend_data){
foreach($friend_data as $friend_key => $friend_value){
if (isset($friend_value['name'])) {
echo $friend_value['name'] . '<br />';
}
}
}

Categories