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
I'm very new to coding.
I'm using PHP to get a JSON response from an API. The JSON response consists of Titles and URLs to pages on the web. The sample JSON response is at the bottom of the page.
How do I write each item in this JSON data using PHP to my HTML page in the body tag? I want to create HTML "a" tags with the text being the JSON name value and the href being the JSON url value for each item.
Where does the JSON data end up after I get it from the API using PHP, and then how do I access it and format it with PHP? I'm using PHP to keep my API access key server side so the client can't see it. Here is my code:
<?php
$accessKey = "12345678";
$endpoint = '*Imaginary API endpoint*';
$term = 'hi';
function APIResponse ($url, $key, $query) {
$headers = "Ocp-Apim-Subscription-Key: $key\r\n";
$options = array ('http' => array (
'header' => $headers,
'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query), false, $context);
$headers = array();
foreach ($http_response_header as $k => $v) {
$h = explode(":", $v, 2);
if (isset($h[1]))
if (preg_match("/^APIs-/", $h[0]) || preg_match("/^X-MSEdge-/", $h[0]))
$headers[trim($h[0])] = trim($h[1]);
}
return array($headers, $result);
}
if (strlen($accessKey) == 8) {
print "Searching the Web for: " . $term . "\n";
list($headers, $json) = APIResponse($endpoint, $accessKey, $term);
print "\nRelevant Headers:\n\n";
foreach ($headers as $k => $v) {
print $k . ": " . $v . "\n";
}
print "\nJSON Response:\n\n";
echo json_encode(json_decode($json), JSON_PRETTY_PRINT);
} else {
print("Invalid API subscription key!\n");
print("Please paste yours into the source code.\n");
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!-- This is the result I'm looking for -->
<?php echo JSON:webPages:value:id ?>
</body>
</html>
JSON Response:
{
"_type": "SearchResponse",
"queryContext": {
"originalQuery": "hi"
},
"webPages": {
"webSearchUrl": "https:\/\/imaginaryapi.com\/search?q=hi",
"totalEstimatedMatches": 65700000,
"value": [
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.0",
"name": "Hi | Define Hi at Dictionary.com",
"url": "https:\/\/www.dictionary.com\/browse\/hi",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.dictionary.com\/browse\/hi",
"snippet": "After you insisted, you write that, \u201cno one from the crew would meet my eyes or say hi.\u201d",
"dateLastCrawled": "2018-10-09T15:57:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.1",
"name": "Fors\u00ed\u00f0a | H\u00e1sk\u00f3li \u00cdslands",
"url": "https:\/\/www.hi.is\/",
"about": [
{
"name": "University of Iceland"
}
],
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.hi.is",
"snippet": "Opi\u00f0 fyrir ums\u00f3knir um innritun \u00ed H\u00e1sk\u00f3la \u00cdslands \u00e1 vormisseri 2019 - Takmarka\u00f0ur hluti n\u00e1mslei\u00f0a \u00ed bo\u00f0i. Ums\u00f3knarfrestur \u00ed framhaldsn\u00e1m til 15. okt\u00f3ber og grunnn\u00e1m til 30. n\u00f3vember",
"deepLinks": [
{
"name": "Vefp\u00f3stur",
"url": "https:\/\/www.hi.is\/haskolinn\/vefpostur"
},
{
"name": "Leit A\u00f0 Starfsf\u00f3lki",
"url": "https:\/\/www.hi.is\/starfsmannaleit"
},
{
"name": "S\u00e6kja Um N\u00e1m",
"url": "https:\/\/ugla.hi.is\/umsoknir\/index.php"
},
{
"name": "Endurmenntun H\u00ed",
"url": "https:\/\/www.hi.is\/nam\/endurmenntun_hi"
},
{
"name": "Stundat\u00f6flur",
"url": "https:\/\/www.hi.is\/laeknadeild\/stundatoflur"
},
{
"name": "Fr\u00e9ttir",
"url": "https:\/\/www.hi.is\/frettir"
}
],
"dateLastCrawled": "2018-10-10T18:35:00.0000000Z",
"language": "is",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.2",
"name": "Hi | Definition of Hi by Merriam-Webster",
"url": "https:\/\/www.merriam-webster.com\/dictionary\/hi",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.merriam-webster.com\/dictionary\/hi",
"snippet": "These example sentences are selected automatically from various online news sources to reflect current usage of the word 'hi.' Views expressed in the examples do not represent the opinion of Merriam-Webster or its editors.",
"dateLastCrawled": "2018-10-10T10:35:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.3",
"name": "HI - Wikipedia",
"url": "https:\/\/en.wikipedia.org\/wiki\/HI",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/en.wikipedia.org\/wiki\/HI",
"snippet": "Hi (or Hello) is a frequent act of greeting or welcoming someone.HI or Hi may also refer to:",
"dateLastCrawled": "2018-10-10T15:53:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.4",
"name": "Hi (#hi) | Twitter",
"url": "https:\/\/twitter.com\/hi",
"thumbnailUrl": "https:\/\/www.bing.com\/th?id=OIP.PqKuxRwx55VE6E--5HFwKQAAAA&pid=Api",
"about": [
{
"name": "Hi"
},
{
"name": "Hi"
}
],
"isFamilyFriendly": true,
"displayUrl": "https:\/\/twitter.com\/hi",
"snippet": "The latest Tweets from Hi (#hi). BYEBYE Hi en daarmee ook dit account. We zijn nog wel in de lucht, maar niet actief. Voor servicevragen kun je terecht bij #KPNwebcare. Doei!. Den Haag, Zuid-Holland",
"dateLastCrawled": "2018-10-05T00:19:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.5",
"name": "H\u00ef Ibiza - Brand-New Club in Ibiza, Spain",
"url": "https:\/\/www.hiibiza.com\/en",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.hiibiza.com\/en",
"snippet": "H\u00ef Ibiza is the brand new club by Ushua\u00efa Entertainment located in the heart of Ibiza clubland, Playa d'en Bossa. The club will stay true to the open-minded spirit of Ibiza, bringing together music lovers to dance, discover and experience the magic of the White Isle.",
"dateLastCrawled": "2018-10-09T13:58:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.6",
"name": "Danielle Bregoli is BHAD BHABIE \u201cHi Bich \/ Whachu Know ...",
"url": "https:\/\/www.youtube.com\/watch?v=1NyMSWqIJDQ",
"about": [
{
"name": "YouTube"
}
],
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.youtube.com\/watch?v=1NyMSWqIJDQ",
"snippet": "\ud83d\udea8STREAM \"Hi Bich\" \ufe0f https:\/\/Atlantic.lnk.to\/hibich \ud83d\udda4\ud83d\udc80\ud83c\udfa4\ud83d\udd25 new songs - \u24f5 video HI BICH & WHACHU KNOW by BHAD BHABIE aka Danielle Bregoli\ud83d\udda4\ud83d\udc45\ud83d\udc34\ud83c\udfc1 produced by Ronn...",
"dateLastCrawled": "2018-10-08T04:50:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.7",
"name": "Hi - Capture. Write. Publish",
"url": "http:\/\/hitotoki.org\/",
"isFamilyFriendly": true,
"displayUrl": "hitotoki.org",
"snippet": "pancakes, Hi Meta, writing Full stack writing (and publishing): Welcome to Hi by Craig Mod. Tokyo \u2014 We\u2019d like to welcome you to Hi: A community of writers, journalists, journalers, illustrators, photographers, travelers, poets, and musicians exploring the world, and sharing those explorations throug...",
"dateLastCrawled": "2018-10-10T20:13:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.8",
"name": "Hi - definition of hi by The Free Dictionary",
"url": "https:\/\/www.thefreedictionary.com\/hi",
"isFamilyFriendly": true,
"displayUrl": "https:\/\/www.thefreedictionary.com\/hi",
"snippet": "2. HI - a state in the United States in the central Pacific on the Hawaiian Islands",
"dateLastCrawled": "2018-10-09T09:35:00.0000000Z",
"language": "en",
"isNavigational": false
},
{
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.9",
"name": "Hi, Hi, Hi - Wikipedia",
"url": "https:\/\/en.wikipedia.org\/wiki\/Hi,_Hi,_Hi",
"about": [
{
"name": "Hi, Hi, Hi"
},
{
"name": "Hi, Hi, Hi"
},
{
"name": "Hi, Hi, Hi"
}
],
"isFamilyFriendly": true,
"displayUrl": "https:\/\/en.wikipedia.org\/wiki\/Hi,_Hi,_Hi",
"snippet": "\"Hi, Hi, Hi\" is a song written by Paul and Linda McCartney and performed by Wings. It was released as a double A-side single with \"C Moon\" in 1972.The song was recorded around the same time as \"C Moon\", in November 1972.",
"snippetAttribution": {
"license": {
"name": "CC-BY-SA",
"url": "http:\/\/creativecommons.org\/licenses\/by-sa\/3.0\/"
},
"licenseNotice": "Text under CC-BY-SA license"
},
"dateLastCrawled": "2018-10-10T20:41:00.0000000Z",
"language": "en",
"isNavigational": false
}
],
"someResultsRemoved": true
},
"rankingResponse": {
"mainline": {
"items": [
{
"answerType": "WebPages",
"resultIndex": 0,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.0"
}
},
{
"answerType": "WebPages",
"resultIndex": 1,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.1"
}
},
{
"answerType": "WebPages",
"resultIndex": 2,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.2"
}
},
{
"answerType": "WebPages",
"resultIndex": 3,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.3"
}
},
{
"answerType": "WebPages",
"resultIndex": 4,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.4"
}
},
{
"answerType": "WebPages",
"resultIndex": 5,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.5"
}
},
{
"answerType": "WebPages",
"resultIndex": 6,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.6"
}
},
{
"answerType": "WebPages",
"resultIndex": 7,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.7"
}
},
{
"answerType": "WebPages",
"resultIndex": 8,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.8"
}
},
{
"answerType": "WebPages",
"resultIndex": 9,
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#WebPages.9"
}
},
{
"answerType": "RelatedSearches",
"value": {
"id": "https:\/\/imaginaryapi.com\/api\/v7\/#RelatedSearches"
}
}
]
}
}
}
To print the data, you can use:
$result = json_decode ( $json, true);
foreach ( $result["webPages"]["value"] as $data)
{
echo "" . $data["name"] . "\n";
}
I like to use json_decode() method returning array instead of object, using true as second parameter, but you can also use it as object if you prefer.
Try this in the javascript section...
document.body.onload = addLink;
function addLink () {
// FIRST method : Embedding php in javascripts
<?php foreach(json_encode($json)->webPages->value as $value) { ?>
// Create a new markup
var newContent = $('<?php echo $value->id ?>');
// And add the text node to your div by it's class / id
$('.link').appendChild(newContent);
<?php } ?>
//////////////
// ...OR... //
//////////////
// SECOND method : Pass php variable (in this case it's JSON object) into javascripts
var json = <? echo json_encode($json)->webPages->value ?>;
json.forEach(function(value){
// Create a new markup
var newContent = $('' + value.id + '');
// And add the text node to your div by it's class / id
$('.link').appendChild(newContent);
});
}
Hopefully it works, because I'm not a daily php coder.
I'm trying to parse Json result below fromAjax response. Foreach CostingItem i need to access to UnitPrice.Amount, but I got error.
Can someone help me to access items?
I got this response from Laravel based webservice.
{
"CostingItem": [{
"#attributes": {
"Description": "Basic Price",
"Quantity": "1",
"PassengerRPH": "1",
"PriceBasis": "Passenger"
},
"UnitPrice": {
"#attributes": {
"Amount": "1823.82",
"OriginalAmount": "1974.32"
}
},
"ExtendedPrice": {
"#attributes": {
"Amount": "1823.82",
"OriginalAmount": "1974.32"
}
},
"Commission": {
"#attributes": {
"Rate": "11.00",
"Type": "P"
}
}
}, {
"#attributes": {
"Description": "Basic Price",
"Quantity": "1",
"PassengerRPH": "2",
"PriceBasis": "Passenger"
},
"UnitPrice": {
"#attributes": {
"Amount": "1823.82",
"OriginalAmount": "1974.32"
}
},
"ExtendedPrice": {
"#attributes": {
"Amount": "1823.82",
"OriginalAmount": "1974.32"
}
},
"Commission": {
"#attributes": {
"Rate": "11.00",
"Type": "P"
}
}
}]
}
here is the script used in Ajax:
$.ajax({
type: "POST",
url: "/public/fetch-bambini",
data: {
id: d,
tipologia: tipologia,
bambini: bambini,
neonati: neonati,
adulti: adulti
},
success: function(response) {
$.each(response.CostingItem, function(k, v) {
console.log(v);
});
}
});
This return this response:
Does anyone know how to filter the posts shown on fullcalendar based on their custom fields?
Example: If I wanted to only show "media == twitter" how would I be able to accomplish this using only one json feed?
I appreciate any ideas.
Example of Json:
{
"id": "1",
"title": "Title",
"description": "Details",
"media": "twitter",
},
{
"id": "2",
"title": "Title",
"description": "Details",
"media": "linkedin",
},
{
"id": "3",
"title": "Title",
"description": "Details",
"media": "facebook",
}
The following is the basic setup I have so far of the fullcalendar which is currently working fine.
Example of FullCalendar code:
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '<? echo '2015-11-01'; ?>',
editable: false,
events: "json.php",
eventClick: function(event) {
if (event.url) {
window.open('#' + event.id,"_self");
return false;
}
}
});
According to above mentioned description as a solution to filter json feed,you need to decode json data into php associative array using json_decode() function and apply filter for specific data while iterating over an associative array.
Please refer the example code snippet to filter json data
<?php $json_data='[
{
"id": "1",
"title": "Title",
"description": "Details",
"media": "twitter"
},
{
"id": "2",
"title": "Title",
"description": "Details",
"media": "linkedin"
},
{
"id": "3",
"title": "Title",
"description": "Details",
"media": "facebook"
}
]';
$result=NULL;
$json_array=json_decode($json_data,true);
if($json_array)
{
foreach($json_array as $json)
{
switch($json['media'])
{
case 'twitter':
$result=$json;
break;
}
}
}
echo json_encode($result);
?>
$result variable will hold the filtered json data.
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.";
}
}