I cannot seem to get data into JSON correctly - php

Hello I have spent quite bit of time trying to get my data to look like this in JSON as a sample:
var json = {
"id": "347_0",
"name": "Nine Inch Nails",
"children": [{
"id": "126510_1",
"name": "Jerome Dillon",
"data": {
"band": "Nine Inch Nails",
"relation": "member of band"
},
"children": [{
"id": "52163_2",
"name": "Howlin' Maggie",
"data": {
"band": "Jerome Dillon",
"relation": "member of band"
},
"children": []
}, {
"id": "324134_3",
"name": "nearLY",
"data": {
"band": "Jerome Dillon",
"relation": "member of band"
},
"children": []
}]
}, {
"id": "173871_4",
"name": "Charlie Clouser",
"data": {
"band": "Nine Inch Nails",
"relation": "member of band"
},
"children": []
}, {
"id": "235952_5",
"name": "James Woolley",
"data": {
"band": "Nine Inch Nails",
"relation": "member of band"
},
"children": []
},
I am using the json_encode function and I know how to make the data into JSON I just cannot seem to create anything that will output the above JSON format...For example I use the following code:
foreach($relations as $rel){
$data[$id]["relationTo"] = $rel["name"];
$data[$id]["relation"] = $rel["relation"];
$id = $id + 1;
}
$id = 0;
foreach($relations as $rel){
$children[$id]["id"] = $id+1;
$children[$id]["name"] = $rel["sname"];
$children[$id]["data"] = $data[$id];
$id = $id + 1;
}
$relationsArray["id"] = 0;
$relationsArray["name"] = $rel["name"];
$relationsArray["children"] = $children;
$json_content = json_encode($relationsArray);
And this outputs:
"id":0,
"name":"Al",
"children":[
{
"id":1,
"name":"Brandon",
"data":{
"relationTo":"Albaraa",
"relation":"Friend"
},
"children":[
]
},
{
"id":2,
"name":"Shen",
"data":{
"relationTo":"Albaraa",
"relation":"Friend"
},
"children":[
]
},
{
"id":3,
"name":"Dan",
"data":{
"relationTo":"Albaraa",
"relation":"Professor"
},
"children":[
]
},
{
"id":4,
"name":"Bob",
"data":{
"relationTo":"Albaraa",
"relation":"Boss"
},
"children":[
]
},
{
"id":5,
"name":"Al",
"data":{
"relationTo":"Albaraa",
"relation":"God Father"
},
"children":[
]
},
{
"id":6,
"name":"Albaraa",
"data":{
"relationTo":"Shen",
"relation":"Friend"
},
"children":[
]
},
{
"id":7,
"name":"Brandon",
"data":{
"relationTo":"Shen",
"relation":"Friend"
},
"children":[
]
},
{
"id":8,
"name":"Dan",
"data":{
"relationTo":"Shen",
"relation":"Professor"
},
"children":[
]
},
{
"id":9,
"name":"Albaraa",
"data":{
"relationTo":"Al",
"relation":"God Son"
},
"children":[
]
},
{
"id":10,
"name":"Bob",
"data":{
"relationTo":"Al",
"relation":"Best Friends"
},
"children":[
]
}
]
}
and so on...but I am not able to get the children of the children as you see above!
Any help would be amazing thank you!
EDIT:
class Child{
public $id;
public $name;
public $children;
public $data;
public function __construct($id, $sname, $data, $rel){
$this->children = array();
$this->data = array();
if ($rel){
$this->id = $id+1;
$this->name = $sname;
$data = array();
$data["relationTo"] = $rel["name"];
$data["relation"] = $rel["relation"];
$this->children[] = new Child($id, $rel["sname"],$data);
}
else {
$this->id = $id+1;
$this->name = $sname;
$this->data = $data;
}
}
}
$childrel = array();
$id = 0;
foreach($relations as $rel){
$childrel[] = new Child($id ,"","", $rel);
$id = $id + 1;
}

You have not declared $children before assigning values to it before foreach loop. Hence declare the array like this and alter the code to this
$children = array();
$id = 0;
foreach($relations as $rel){
$children[$id]["id"] = $id+1;
$children[$id]["name"] = $rel["sname"];
$children[$id]["data"] = $data[$id];
$id = $id + 1;
}

Related

Nested json data - retrieve by value

I need to calculate total of profit of a given product in a given year (one or multiple).
I can run nested foreach loops but I want to learn if I can do it in a shorter/cleaner way because I may want to filter data by more conditions. The example below is by using Product Id. The data example is below the php code. There are always two products and two profit values however there maybe additional product attributes e.g. color, size (s, m, l) etc.
$data = json_decode($data_json, true);
$products = $data['products'];
..
$admin_pid = 'bench33';
$admin_years = [2019, 2020];
$profit = 0;
foreach($products as $product) {
foreach($product['sales'] as $sale) {
if($sale['product1']['pid'] == $admin_pid) {
$profit += $sale['profit1'];
} else if($sale['product2']['pid'] == $admin_pid) {
$profit += $sale['profit2'];
}
}
}
echo "Profit for {$admin_pid} is: ".$profit;
This is how my data looks like ...
{
"name": "Furniture Inc.",
"products":
[
{
"team": "Downtown",
"sales":
[
{
"date": "2014-08-16",
"product1": {
"pid": "dining13",
"name": "Dining Table"
},
"product2": {
"pid": "office13",
"name": "Office Table"
},
"profit1": 5,
"profit2": 3
},
]
},
{
"team": "TheMall",
"sales":
[
{
"date": "2019-03-16",
"product1": {
"pid": "chair11",
"name": "Dining Chair"
},
"product2": {
"pid": "bench33",
"name": "Garden Bench"
},
"profit1": 9,
"profit2": 11
},
]
},
{
"team": "CityCentre",
"sales":
[
{
"date": "2020-08-16",
"product1": {
"pid": "dining13",
"name": "Dining Table"
},
"product2": {
"pid": "bench33",
"name": "Garden Bench"
},
"profit1": 33,
"profit2": 21
},
]
},
]
}

How I can read and update the nested JSON in PHP

I am new to PHP and have little experience with PHP arrays, I have this below JSON file.
$json2=
'{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
}
}
}';
I want to update the values for 'location', 'vmSize','sku','publisher','offer' in the above JSON,
"location" : "eastus"
"vmSize" : "Standard_D3_v2"
"sku" : "20h1-evd"
"publisher" : "MicrosoftWindowsDesktop"
"offer" : "windows-10"
I have tried to do the following to this but I am nowhere near navigating the array correctly.
$arr = json_decode($json2, true);
print_r($arr);
Can anyone please help here?
Just try this code
<?php
$json2=
'{
"location": "westus",
"properties": {
"hardwareProfile": {
"vmSize": "Standard_D1_v2"
},
"storageProfile": {
"imageReference": {
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"name": "myVMosdisk",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/networkInterfaces/{existing-nic-name}",
"properties": {
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}"
},
"diagnosticsProfile": {
"bootDiagnostics": {
"storageUri": "http://{existing-storage-account-name}.blob.core.windows.net",
"enabled": true
}
}
}
}';
$arr = json_decode($json2, true);
$arr['location'] = "eastus";
$arr['properties']['hardwareProfile']['vmSize'] = "Standard_D3_v2";
$arr['properties']['storageProfile']['imageReference']['sku'] = "20h1-evd";
$arr['properties']['storageProfile']['imageReference']['publisher'] = "MicrosoftWindowsDesktop";
$arr['properties']['storageProfile']['imageReference']['offer'] = "WindowsServer";
$updatedJson = json_encode($arr);
print_r($updatedJson);
First you need to try json_decode to make an array from this json file and then based on the array schema you need to find the property that you want and update it and then again use the json_encode to make an json

Finding State Short Name from JSON file with PHP

I have a JSON file that have all list of all the countries with their cities, and state. The file has this structure
"NO": {
"name": "Norway",
"states": {
"VA": {
"name": "Vest-Agder"
},
"RO": {
"name": "Rogaland"
},
"HO": {
"name": "Hordaland"
},
"SF": {
"name": "Sogn og Fjordane"
},
"MR": {
"name": "Møre og Romsdal"
},
"ST": {
"name": "Sør-Trøndelag"
},
"NO": {
"name": "Nord-Trøndelag"
},
"NT": {
"name": "Nordland"
},
"TR": {
"name": "Troms"
},
"FI": {
"name": "Finnmark"
},
"SJ": {
"name": "Svalbard"
},
"SJ": {
"name": "Jan Mayen"
},
"AK": {
"name": "Akershus"
},
"AA": {
"name": "Aust-Agder"
},
"BU": {
"name": "Buskerud"
},
"HE": {
"name": "Hedmark"
},
"OP": {
"name": "Oppland"
},
"OS": {
"name": "Oslo"
},
"TE": {
"name": "Telemark"
},
"VF": {
"name": "Vestfold"
},
"OF": {
"name": "Østfold"
}
}
},
What I am trying to achieve is to get the short name of state when user input the full name in the input field. For example if they add "Oslo" I will get "OS" in output
This is the code that I came up with but I am not getting the output.
$jsonitem = file_get_contents("countries-info.json");
$objitems = json_decode($jsonitem);
$findByname = function($name) use ($objitems) {
foreach ($objitems as $friend) {
if ($friend->name == $name) return $friend->state;
}
return false;
};
echo $findByname($_GET[code]) ?: 'No record found.';
Need advise.
Looking at the structure of your JSON you should loop $objitems->NO->states ( $objitems will contain the complete object, you only want the states)
So you need to change your foreach to:
foreach ($objitems->NO->states as $short => $state) {
if ($state->name == $name) return $short;
}
foreach ($objitems as $state => $friend) {
if ($friend->name == $name) return $state;
}

JSON Parsing Multi Level

How I can get text from below JSON.
https://jsfiddle.net/7h6a55m6/2/ JSON Data
Need to get "Testing","Testing2", etc. Stuck in multi level JSON style. Whats the easiest way to do
foreach ($response->data as $res) {
echo $res['comments'];
}
Use the json_decode().Something like below
$test_json='
{ "media":
{ "data":
[
{ "comments":
{ "data":
[
{ "text": "Testing", "id": "17935572247064063" },
{ "text": "Testing2", "id": "17909467621160083" },
{ "text": "Testing3", "id": "17879193508206704" },
{ "text": "Testing4", "id": "17936230114007492" },
{ "text": "Testing5", "id": "17861359981236880" },
{ "text": "Testing6", "id": "17932586956016890" },
{ "text": "Testing7", "id": "17920569544116678" },
{ "text": "Testing8", "id": "17933592700059204" }
]
}
}
]
}
}
';
$test_json=json_decode($test_json,true);
foreach($test_json['media']['data'][0]['comments']['data'] as $row){
print_r($row['text']);
}
try
$responseData = json_decode($response->data, true);
$result = $responseData['media']['data'][0]['comments']['data'];
foreach($result as $data) {
// do your stuff here
}

How to display company name "only" on friends work history (facebook api)

I have been getting my facebook friends work history. But the result is an array whose content is as follows :
{
"id": "xxx",
"friends": {
"data": [
{
"name": "Indiarto Priadi",
"work": [
{
"employer": {
"id": "111178415566505",
"name": "Liputan 6 SCTV"
}
},
{
"employer": {
"id": "107900732566334",
"name": "SCTV"
}
}
],
"id": "502163984"
},
{
"name": "Agustin Kertawijaya",
"work": [
{
"employer": {
"id": "138215336225242",
"name": "Trader Corporation (Canada)"
},
"location": {
"id": "110941395597405",
"name": "Toronto, Ontario"
},
"position": {
"id": "168673399850791",
"name": "Desktop operator <Pre press>"
},
"start_date": "2006-06-01",
"end_date": "2008-06-01"
},
{
"employer": {
"id": "114464911939560",
"name": "Merrill Corporation Canada"
},
"location": {
"id": "110941395597405",
"name": "Toronto, Ontario"
},
"position": {
"id": "190075304347365",
"name": "Financial Print Project Manager"
},
"start_date": "2006-06-01",
"end_date": "2011-10-01"
}
],
"id": "511990261"
}
],
"paging": {
"next": "https://graph.facebook.com/1065251285/friends?limit=2&fields=name,work&offset=2&__after_id=511990261"
}
}
}
Now i want to display "only" the employer name on my page, but i can't find the way to do that.
Here is my code :
$userFriends = $facebook->api('/'.$userId.'/friends');
for($i=0;$i<=3;$i++){ //retrieved friends (max 4 persons)
$value=$userFriends["data"][$i];
echo "<div id='$value[id]'>";
$profile = $facebook->api("/".$value["id"]);
$friendsWork = $facebook->api("/".$value["id"]."?fields=work");
echo "<strong>".$profile["name"]."<br></strong>";
echo " <img src='https://graph.facebook.com/".$value["id"]."/picture'><br>";
echo "Username : ".$profile["username"]."<br>";
echo "Local : ".$profile["locale"]."<br>";
echo "Birthdate : ".$profile["birthday"]."<br>";
print_r($friendsWork); // <--- the result is an array
echo "<hr>";
echo "</div>";
}
Does anyone know how to display the company(employer) name only?
any answers would be greatly appreciated. Thank You
Here you go, nothing fancy, I just did what I said in my comment
$json = '{
"id": "xxx",
"friends": {
"data": [
{
"name": "Indiarto Priadi",
"work": [
{
"employer": {
"id": "111178415566505",
"name": "Liputan 6 SCTV"
}
},
{
"employer": {
"id": "107900732566334",
"name": "SCTV"
}
}
],
"id": "502163984"
},
{
"name": "Agustin Kertawijaya",
"work": [
{
"employer": {
"id": "138215336225242",
"name": "Trader Corporation (Canada)"
},
"location": {
"id": "110941395597405",
"name": "Toronto, Ontario"
},
"position": {
"id": "168673399850791",
"name": "Desktop operator <Pre press>"
},
"start_date": "2006-06-01",
"end_date": "2008-06-01"
},
{
"employer": {
"id": "114464911939560",
"name": "Merrill Corporation Canada"
},
"location": {
"id": "110941395597405",
"name": "Toronto, Ontario"
},
"position": {
"id": "190075304347365",
"name": "Financial Print Project Manager"
},
"start_date": "2006-06-01",
"end_date": "2011-10-01"
}
],
"id": "511990261"
}
],
"paging": {
"next": "https://graph.facebook.com/1065251285/friends?limit=2&fields=name,work&offset=2&__after_id=511990261"
}}}'; // remember the last two closing curlys, you left them out of the code block in the OP.
$obj = json_decode($json);
foreach ($obj->friends->data as $friend) {
echo '<h1>' . $friend->name . '</h1>';
foreach ($friend->work as $job) {
echo 'Employee: ' . $job->employer->name . '<br/>';
}
echo '<hr>';
}
Output:
Indiarto Priadi
Employee: Liputan 6 SCTV
Employee: SCTV
--------------------------------------
Agustin Kertawijaya
Employee: Trader Corporation (Canada)
Employee: Merrill Corporation Canada
--------------------------------------
You just have to parse the array you obtained, like this-
$userFriends = $facebook->api('/'.$userId.'/friends?fields=work,name');
foreach($userFriends['data'] as $friend)
{
$friend_name = $friend['name'];
$emp_name=array();
// list of all employers of this friend
if(isset($friend['work']))
{
foreach($friend['work'] as $work)
{
array_push($emp_name, $work['employer']['name']);
}
}
else
{
$emp_name = "N.A.";
}
}

Categories