json file malformed - how to find out where? - php

I'm developing website using weatherapi. I intend to fetch weather using cityid which is in citylist.json file. Users wil enter city name, I was hoping to extract cityid from this json and use the cityid to fetch weather using api. But there is some error in json.
if (file_exists('citylist.json')) {
$cityArray = file_get_contents("citylist.json");
$cityAA = json_decode($cityArray,true);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
print_r($cityAA);
}
The json is around 12mb. Here are first few lines
{
"_id": 14256,
"coord": {
"lon": 48.570728,
"lat": 34.790878
},
"country": "IR",
"geoname": {
"cl": "P",
"code": "PPL",
"parent": 132142
},
"langs": [{
"de": "Azad Shahr"
},
{
"fa": "آزادشهر"
}],
"name": "Azadshahr",
"stat": {
"level": 1.0,
"population": 514102
},
"stations": [{
"id": 7030,
"dist": 9,
"kf": 1
}],
"zoom": 10
}{
"_id": 18918,
"coord": {
"lon": 34.058331,
"lat": 35.012501
},
"country": "CY",
"geoname": {
"cl": "P",
"code": "PPL",
"parent": 146615
},
"langs": [{
"en": "Protaras"
},
{
"ru": "Протарас"
}],
"name": "Protaras",
"stat": {
"level": 1.0,
"population": 20230
},
"stations": [{
"id": 5448,
"dist": 42,
"kf": 1
}],
"zoom": 6
}
I've tried jsonlint but the file is too big I guess.
The var_dump suggests Syntax error, malformed JSON. I cannot post the image as i'm not allowed.
How can I find out where the json is malformed?

This site can help you: http://jsonlint.com/
In the example provided you can't just pass 2 objects like you did. You need to put it inside an array.
[obj,obj2]
Fixed:
[{
"_id": 14256,
"coord": {
"lon": 48.570728,
"lat": 34.790878
},
"country": "IR",
"geoname": {
"cl": "P",
"code": "PPL",
"parent": 132142
},
"langs": [{
"de": "Azad Shahr"
}, {
"fa": "آزادشهر"
}],
"name": "Azadshahr",
"stat": {
"level": 1.0,
"population": 514102
},
"stations": [{
"id": 7030,
"dist": 9,
"kf": 1
}],
"zoom": 10
}, {
"_id": 18918,
"coord": {
"lon": 34.058331,
"lat": 35.012501
},
"country": "CY",
"geoname": {
"cl": "P",
"code": "PPL",
"parent": 146615
},
"langs": [{
"en": "Protaras"
}, {
"ru": "Протарас"
}],
"name": "Protaras",
"stat": {
"level": 1.0,
"population": 20230
},
"stations": [{
"id": 5448,
"dist": 42,
"kf": 1
}],
"zoom": 6
}]

It looks like the file contains multiple JSON objects but not well integrated.
This is valid JSON:
{
"_id": 14256,
"coord": {
"lon": 48.570728,
"lat": 34.790878
},
"country": "IR",
"geoname": {
"cl": "P",
"code": "PPL",
"parent": 132142
},
"langs": [{
"de": "Azad Shahr"
},
{
"fa": "آزادشهر"
}],
"name": "Azadshahr",
"stat": {
"level": 1.0,
"population": 514102
},
"stations": [{
"id": 7030,
"dist": 9,
"kf": 1
}],
"zoom": 10
}
And this is too:
{
"_id": 18918,
"coord": {
"lon": 34.058331,
"lat": 35.012501
},
"country": "CY",
"geoname": {
"cl": "P",
"code": "PPL",
"parent": 146615
},
"langs": [{
"en": "Protaras"
},
{
"ru": "Протарас"
}],
"name": "Protaras",
"stat": {
"level": 1.0,
"population": 20230
},
"stations": [{
"id": 5448,
"dist": 42,
"kf": 1
}],
"zoom": 6
}
But how they are put together, it is not. That might be a problem of the JSON file imported or if you are generating it by yourself from the API.
A valid JSON would be formed like an array of those objects:
[{
"_id": 14256,
"coord": {
"lon": 48.570728,
"lat": 34.790878
},
"country": "IR",
"geoname": {
"cl": "P",
"code": "PPL",
"parent": 132142
},
"langs": [{
"de": "Azad Shahr"
}, {
"fa": "آزادشهر"
}],
"name": "Azadshahr",
"stat": {
"level": 1.0,
"population": 514102
},
"stations": [{
"id": 7030,
"dist": 9,
"kf": 1
}],
"zoom": 10
}, {
"_id": 18918,
"coord": {
"lon": 34.058331,
"lat": 35.012501
},
"country": "CY",
"geoname": {
"cl": "P",
"code": "PPL",
"parent": 146615
},
"langs": [{
"en": "Protaras"
}, {
"ru": "Протарас"
}],
"name": "Protaras",
"stat": {
"level": 1.0,
"population": 20230
},
"stations": [{
"id": 5448,
"dist": 42,
"kf": 1
}],
"zoom": 6
}]
PS: You can use http://jsonlint.com/ to check valid JSON.

I tried to convert the json file into an array of multiple json snippets using the below function
function json_split_objects($json){
$q = FALSE;
$len = strlen($json);
for($l=$c=$i=0;$i<$len;$i++)
{
$json[$i] == '"' && ($i>0?$json[$i-1]:'') != '\\' && $q = !$q;
if(!$q && in_array($json[$i], array(" ", "\r", "\n", "\t"))){continue;}
in_array($json[$i], array('{', '[')) && !$q && $l++;
in_array($json[$i], array('}', ']')) && !$q && $l--;
(isset($objects[$c]) && $objects[$c] .= $json[$i]) || $objects[$c] = $json[$i];
$c += ($l == 0);
}
return $objects;
}
if (file_exists('current_cities.json')) {
echo "here";
$cityJson = file_get_contents("current_cities.json");
$city_json_data_array = json_split_objects($cityJson);
But this did not work, below was the split array generated but it did not put comma(,) between the snippets.
Array
(
[0] => {"_id":14256,"coord":{"lon":48.570728,"lat":34.790878},"country":"IR","geoname":{"cl":"P","code":"PPL","parent":132142},"langs":[{"de":"Azad Shahr"},{"fa":"آزادشهر"}],"name":"Azadshahr","stat":{"level":1.0,"population":514102},"stations":[{"id":7030,"dist":9,"kf":1}],"zoom":10}
[1] => {"_id":18918,"coord":{"lon":34.058331,"lat":35.012501},"country":"CY","geoname":{"cl":"P","code":"PPL","parent":146615},"langs":[{"en":"Protaras"},{"ru":"Протарас"}],"name":"Protaras","stat":{"level":1.0,"population":20230},"stations":[{"id":5448,"dist":42,"kf":1}],"zoom":6}
[2] => {"_id":23814,"coord":{"lon":47.055302,"lat":34.383801},"country":"IR","geoname":{"cl":"P","code":"PPL","parent":128222},"langs":[{"fa":"کهریز"}],"name":"Kahriz","stat":{"level":1.0,"population":766706},"stations":[{"id":7022,"dist":10,"kf":1}],"zoom":7}
[3] => {"_id":24851,"coord":{"lon":47.9725,"lat":34.073399},"country":"IR","geoname":{"cl":"P","code":"PPL","parent":125605},"langs":[{"fa":"نور آباد"},{"link":"http://en.wikipedia.org/wiki/Nurabad%2C_Lorestan"},{"ru":"Нурабад"}],"name":"Nurabad","stat":{"level":1.0,"population":73528},"stations":[{"id":7022,"dist":80,"kf":1},{"id":7024,"dist":75,"kf":1},{"id":7073,"dist":49,"kf":1}],"zoom":9}
[4] => {"_id":32723,"coord":{"lon":52.309422,"lat":35.23455},"country":"IR","geoname":{"cl":"P","code":"PPL","parent":116401},"langs":[{"fa":"ايستگاه گرمسار"}],"name":"Istgah-e Garmsar","stat":{"level":1.0,"population":49491},"stations":[{"id":7036,"dist":99,"kf":1}],"zoom":8}
[5] => {"_id":32767,"coord":{"lon":51.56889,"lat":35.439442},"country":"IR","geoname":{"cl":"P","code":"PPL","parent":110791},"langs":[{"fa":"قرچك"}],"name":"Qarchak","stat":{"level":1.0,"population":251834},"stations":[{"id":7032,"dist":36,"kf":1},{"id":7074,"dist":48,"kf":1}],"zoom":9}
[6] => {"_id":41210,"coord":{"lon":49.195999,"lat":36.213001},"country":"IR","geoname":{"cl":"P","code":"PPL","parent":111452},"langs":[{"fa":"خرم درّه"}],"name":"Khorram Darreh","stat":{"level":1.0,"population":50528},"stations":[{"id":7033,"dist":76,"kf":1}],"zoom":12}
[7] => {"_id":50672,"coord":{"lon":44.893799,"lat":2.6185},"country":"SO","geoname":{"cl":"P","code":"PPL","parent":51966},"langs":[{"so":"Wanlaweyn"}],"name":"Wanlaweyn","stat":{"level":1.0,"population":22022},"zoom":9}
[8] => {"_id":52867,"coord":{"lon":44.529991,"lat":1.78784},"country":"SO","geoname":{"cl":"P","code":"PPLA2","parent":51966},"langs":[{"so":"Qoryooley"}],"name":"Qoryooley","stat":{"level":1.0,"population":51720},"zoom":8}
[9] => {"_id":53157,"coord":{"lon":49.872822,"lat":11.47197},"country":"SO","geoname":{"cl":"P","code":"PPL","parent":64661},"langs":[{"link":"http://en.wikipedia.org/wiki/Qandala"},{"so":"Qandala"}],"name":"Qandala","stat":{"level":1.0,"population":15923},"zoom":8}
[10] => {"_id":53654,"coord":{"lon":45.34375,"lat":2.03711},"country":"SO","geoname":{"cl":"P","code":"PPLC","parent":64833},"name":"Mogadishu","stat":{"level":1.0,"population":2587183},"zoom":1}
[11] => {"_id":54715,"coord":{"lon":42.544498,"lat":3.79376},"country":"SO","geoname":{"cl":"P","code":"PPL","parent":58802},"name":"Luuq","stat":{"level":1.0,"population":33820},"zoom":8}
[12] => {"_id":55671,"coord":{"lon":42.545361,"lat":-0.35817},"country":"SO","geoname":{"cl":"P","code":"PPLA","parent":56083},"langs":[{"de":"Kismaayo"},{"en":"Kismayo"},{"es":"Kismaayo"},{"fi":"Kismayo"},{"fr":"Kismaayo"},{"id":"Kismaayo"},{"ja":"キスマヨ"},{"link":"http://en.wikipedia.org/wiki/Kismayo"},{"nl":"Kismayo"},{"so":"Kismaayo"},{"sw":"Kismayu"}],"name":"Kismaayo","stat":{"level":1.0,"population":234852},"zoom":6}
[13] => {"_id":56166,"coord":{"lon":42.785351,"lat":0.48829},"country":"SO","geoname":{"cl":"P","code":"PPL","parent":56084},"langs":[{"link":"http://en.wikipedia.org/wiki/Jilib"},{"ru":"Джилиб"}],"name":"Jilib","stat":{"level":1.0,"population":43694},"zoom":9}
[14] => {"_id":56335,"coord":{"lon":45.500481,"lat":2.78087},"country":"SO","geoname":{"cl":"P","code":"PPLA","parent":51967},"langs":[{"de":"Giohar"},{"en":"Giohar"},{"link":"http://en.wikipedia.org/wiki/Jowhar"},{"so":"Jawhar"}],"name":"Jawhar","stat":{"level":1.0,"population":47086},"zoom":8}
[15] => {"_id":56399,"coord":{"lon":42.744968,"lat":0.06968},"country":"SO","geoname":{"cl":"P","code":"PPL","parent":56083},"langs":[{"de":"Jamaame"},{"en":"Jamaame"},{"link":"http://en.wikipedia.org/wiki/Jamame"}],"name":"Jamaame","stat":{"level":1.0,"population":185270},"zoom":6}
I was thinking of fetching the "_id" using the $city variable which the user enters
for($i = 0, $size = count($city_json_data_array); $i < $size; ++$i) {
if ($city_json_data_array[$i].['name'] == $city){
$cityId = $city_json_data_array[$i]['_id'];
print_r($cityId);
}
}

So the JSON file was indeed not correct, I had to use str_replace() and write the file using file_put_contents() to create a new valid json file.
This is my working code
if (isset($_GET['city']) && $_GET['city']){
$city = ucwords($_GET['city']);
if (file_exists('currentCityArray.json')) {
$cityArray = file_get_contents("currentCityArray.json");
$decodedArray="";
$decodedArray = json_decode($cityArray, true);
//print_r($decodedArray);
//Search the $decodedArray to match city name entered by the user and fetch the cityID for that city
for($i = 0, $size = count($decodedArray);$i<$size; $i++) {
if ($decodedArray[$i]['name'] == $city){
$cityId = $decodedArray[$i]['_id'];
}
}
if(!$cityId){
$error .= $city." city could not be found in our database. Please enter a valid city name.";
}else{
//Fetch the weather contents by using $cityId
$urlContents = file_get_contents("http://api.openweathermap.org/data/2.5/forecast?id=".urlencode($cityId)."&APPID=0934a70098e84dc720b8d7f07bb1202d");
// added a flag 'true' to retrieve the data in $weatherArray as associative array
$weatherArray = json_decode($urlContents, true);
//print_r ($weatherArray);
if($weatherArray['cod']=="200"){
//print_r($weatherArray);
$weatherInfo = "The weather in ".$city." is currently '".$weatherArray['list'][0]['weather'][0]['description']."'";
$tempCelcius = intval($weatherArray['list'][0]['main']['temp'] - 273);
$weatherInfo .= ". The average temperature is expected to be about: ".$tempCelcius."°C";
$windSpeed = $weatherArray['list'][0]['wind']['speed'];
$weatherInfo .= ". The wind speed is currently ".$windSpeed."m/s.";
}else{
$error .= $city." city could not be found in our database. Please enter a valid city name.";
}
}
}else{
$error .= "Crikey ! the file with the list of cities has gone missing!";
}
}

Related

Extract element from nested JSON

There is json response:
{
"id": "1234567890123456789",
"creation_date": 12345678,
"event": "WAITING_PAYMENT",
"version": "2.0.0",
"data": {
"product": {
"id": 213344,
"name": "Product Name",
"has_co_production": false
},
"affiliates": [
{
"name": "Affiliate name"
}
],
"buyer": {
"email": "buyer#email.com"
},
"producer": {
"name": "Producer Name"
},
"commissions": [
{
"value": 0.65,
"source": "MARKETPLACE"
},
{
"value": 3.10,
"source": "PRODUCER"
}
],
"purchase": {
"approved_date": 1231241434453,
"full_price": {
"value": 134.0
},
"original_offer_price": {
"currency_value": "EUR"
"value": 100.78,
},
"price": {
"value": 150.6
},
"order_date": "123243546",
"status": "STARTED",
"transaction": "HP02316330308193",
"payment": {
"billet_barcode": "03399.33335 33823.303087 198801027 2 876300015000",
"billet_url": "https://billet-link.com/bHP023163303193",
}
},
"subscription": {
"status": "ACTIVE",
"plan": {
"name": "plan name"
},
"subscriber": {
"code": "12133421"
}
}
}
}
My question is how to extract data["buyer"]["email"] in PHP ?
I only need to extract the email information from the buyer table inside the data table.
First, you need to decode the json to a PHP array (or an object), then you can access the requested information from the decoded data.
$data = json_decode('the json string most place here', true);
$email = $data['buyer']['email'];
Place your json string in the first argument of json_decode() function.

How to count same value from a php array

i have a json of specification of a mobile, i want to count repeated value of a particular node. my json in as below:
[{
"other": {
"1": {
"type": "Network",
"label": "Technology",
"value": "GSM / HSPA / LTE"
},
"2": {
"type": "Network",
"label": "2G bands",
"value": "GSM 850 / 900 / 1800 / 1900 - SIM 1 & SIM 2"
},
"3": {
"type": "Network",
"label": "3G bands",
"value": "HSDPA 850 / 900 / 1900 / 2100"
},
"4": {
"type": "Network",
"label": "4G bands",
"value": "LTE band 1(2100), 3(1800), 5(850), 7(2600), 8(900), 20(800), 38(2600), 40(2300), 41(2500)"
},
"5": {
"type": "Network",
"label": "Speed",
"value": "HSPA 42.2/5.76 Mbps, LTE-A (2CA) Cat12 600/50 Mbps"
},
"6": {
"type": "Network",
"label": "GPRS",
"value": "Yes"
},
"7": {
"type": "Network",
"label": "EDGE",
"value": "Yes"
},
"8": {
"type": "Launch",
"label": "Announced",
"value": "2019, January"
},
"9": {
"type": "Launch",
"label": "Status",
"value": "Available. Released 2019, February"
},
"10": {
"type": "Body",
"label": "Dimensions",
"value": "156.4 x 74.5 x 8.8 mm (6.16 x 2.93 x 0.35 in)"
},
"11": {
"type": "Body",
"label": "Weight",
"value": "186 g (6.56 oz)"
},
"12": {
"type": "Body",
"label": "SIM",
"value": "Dual SIM (Nano-SIM, dual stand-by)"
},
"13": {
"type": "Display",
"label": "Type",
"value": "PLS TFT capacitive touchscreen, 16M colors"
},
"14": {
"type": "Display",
"label": "Size",
"value": "6.3 inches, 97.4 cm2 (~83.6% screen-to-body ratio)"
},
"15": {
"type": "Display",
"label": "Resolution",
"value": "1080 x 2340 pixels, 19.5:9 ratio (~409 ppi density)"
},
"16": {
"type": "Platform",
"label": "OS",
"value": "Android 8.1 (Oreo); Experience 9.5"
},
"17": {
"type": "Platform",
"label": "Chipset",
"value": "Exynos 7904 (14 nm)"
},
"18": {
"type": "Platform",
"label": "CPU",
"value": "Octa-core (2x1.8 GHz Cortex-A73 & 6x1.6 GHz Cortex-A53)"
},
"19": {
"type": "Platform",
"label": "GPU",
"value": "Mali-G71 MP2"
},
"20": {
"type": "Memory",
"label": "Card slot",
"value": "microSD, up to 1 TB (dedicated slot)"
},
"21": {
"type": "Memory",
"label": "Internal",
"value": "64 GB, 4 GB RAM or 32 GB, 3 GB RAM"
},
"22": {
"type": "Main Camera",
"label": "Dual",
"value": "13 MP, f/1.9, 1/3.1\", 1.12um, PDAF"
},
"23": {
"type": "Main Camera",
"label": "Dual",
"value": "5 MP, f/2.2, 12mm (ultrawide)"
},
"24": {
"type": "Main Camera",
"label": "Features",
"value": "LED flash, panorama, HDR"
},
"25": {
"type": "Main Camera",
"label": "Video",
"value": "1080p#30fps"
},
"26": {
"type": "Selfie camera",
"label": "Single",
"value": "8 MP, f/2.0, 25mm (wide)"
},
"27": {
"type": "Selfie camera",
"label": "Features",
"value": "HDR"
},
"28": {
"type": "Selfie camera",
"label": "Video",
"value": "1080p#30fps"
},
"29": {
"type": "Sound",
"label": "Loudspeaker",
"value": "Yes"
},
"30": {
"type": "Sound",
"label": "3.5mm jack",
"value": "Yes"
},
"31": {
"type": "Sound",
"value": "Active noise cancellation with dedicated mic"
},
"32": {
"type": "Sound",
"value": "Dolby Atmos sound"
},
"33": {
"type": "Comms",
"label": "WLAN",
"value": "Wi-Fi 802.11 b/g/n, WiFi Direct, hotspot"
},
"34": {
"type": "Comms",
"label": "Bluetooth",
"value": "5.0, A2DP, LE"
},
"35": {
"type": "Comms",
"label": "GPS",
"value": "Yes, with A-GPS, GLONASS, BDS"
},
"36": {
"type": "Comms",
"label": "Radio",
"value": "FM radio, RDS, recording"
},
"37": {
"type": "Comms",
"label": "USB",
"value": "2.0, Type-C 1.0 reversible connector"
},
"38": {
"type": "Features",
"label": "Sensors",
"value": "Fingerprint (rear-mounted), accelerometer, gyro, proximity, compass"
},
"39": {
"type": "Battery",
"value": "Non-removable Li-Po 5000 mAh battery"
},
"40": {
"type": "Battery",
"label": "Charging",
"value": "Fast battery charging 15W"
},
"41": {
"type": "Misc",
"label": "Colors",
"value": "Ocean Blue, Charcoal Black"
},
"42": {
"type": "Misc",
"label": "Models",
"value": "SM-M205F, SM-M205FN, SM-M205G"
},
"43": {
"type": "Misc",
"label": "SAR EU",
"value": "0.25 W/kg (head) 1.59 W/kg (body)"
},
"44": {
"type": "Misc",
"label": "Price",
"value": "About 220 EUR"
},
"45": {
"type": "Tests",
"label": "Performance",
"value": "Basemark OS II: 1846 / Basemark OS II 2.0: 2025Basemark X: 8434"
},
"46": {
"type": "Tests",
"label": "Display",
"value": "Contrast ratio: 1333:1 (nominal), 2.960 (sunlight)"
},
"47": {
"type": "Tests",
"label": "Camera",
"value": "Photo / Video"
},
"48": {
"type": "Tests",
"label": "Loudspeaker",
"value": "Voice 67dB / Noise 66dB / Ring 68dB"
},
"49": {
"type": "Tests",
"label": "Audio quality",
"value": "Noise -90.5dB / Crosstalk -91.7dB"
},
"50": {
"type": "Tests",
"label": "Battery life",
"value": "Endurance rating 103h"
}
}
}]
I want to count how many times Network, Body, Display ..., Tests are there in this JSON.
I have tried below code but unable to found exact information regarding the same
$arr1 = above shared json;
$arr1 = json_decode($arr, true);
foreach ($arr1 as $key=>$value){
$other = $value['other']; //array
$counter = 0;
$lenOther = count($other); //get length of other array
//reading each element of other array
foreach($other as $k=>$v){
$other[$k] = array_count_values($v);
print_r($other[$k]);
}
}
Any modification or suggestion of this question would be appreciated.
Apply array_count_values() along with array_column
$arr1 = json_decode($arr, true);
print_r(array_count_values(array_column($arr1[0]['other'],'type')));
Output:- https://3v4l.org/ZHRIa
Note:- If you want to combine all of them based on type and want to create same structure what you have:-
$arr1 = json_decode($arr, true);
$finalArray = array();
foreach($arr1[0]['other'] as $key=>$value){
$finalArray[$value['type']][] = $value;
}
$newArray = [];
$newArray[] = array('other'=>$finalArray);
print_r($newArray);
Output:- https://3v4l.org/lUrgv
You get the count by using array_count_values method with array_map
just like below
array_count_values(array_map(function($foo) {
return $foo['type'];
}, $arr['other']));
this will get you the count for each type
you can use foreach with array_key_exists
$jarr = json_decode($json,true);
$r = [];
foreach($jarr[0]['other'] as $v){
array_key_exists($v['type'], $r) ? ($r[$v['type']]+=1) : ($r[$v['type']]=1);
}
Working example

Parsing Json into php table results in Undefined index

I am accessing API for "ConnectWise". the data comes into JSON format. i was able to parse the data into table via PHP. however, empty fields in JSON results in Undefined index. This happens for some items with no website, or address for example. the rest shows up fine.
Any help or input would be appreciated.
Here is my code to get the data from Connectwise:
function get_companies(){
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_URL, "https://api-
na.myconnectwise.net/v4_6_release/apis/3.0/company/companies");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Basic (OUR KEY)",
'Content-type: application/json'
));
$result = curl_exec($curl);
curl_close($curl);
$decoded = json_decode($result,true);
return $decoded;
}
And to display the data:
function list_all_accounts(){
$accounts = get_companies();
if ( !empty ($accounts)){
foreach ($accounts as $account) {
{
echo "
</td>
<td>
$account[id]
</td>
<td>
$account[name]
</td>
<td>
$account[addressLine1]
</td>
<td>
$account[phoneNumber]
</td>
<td>
$account[website]
</td>
<td>
$account[name]
</td>
</tr>";
}
}
}
}
Update - Json Sample
[
{
"id": 250,
"identifier": "company name ",
"name": "company name",
"status": {
"id": 1,
"name": "Active",
"_info": {
"status_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/statuses/1"
}
},
"type": {
"id": 1,
"name": "Client",
"_info": {
"type_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/types/1"
}
},
"addressLine1": "address line 1",
"city": "New York",
"state": "NY",
"zip": "11111",
"country": {
"id": 1,
"name": "United States",
"_info": {
"country_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/countries/1"
}
},
"phoneNumber": "123456789",
"faxNumber": "",
"website": "www.site.com",
"territoryId": 2,
"accountNumber": "",
"dateAcquired": "2006-06-21T04:00:00Z",
"sicCode": {
"id": 1209,
"name": "consulting"
},
"annualRevenue": 0,
"timeZone": {
"id": 1,
"name": "GMT-5/Eastern Time: US & Canada",
"_info": {
"timeZoneSetup_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/system/timeZoneSetups/1"
}
},
"leadFlag": false,
"unsubscribeFlag": false,
"userDefinedField5": "1",
"taxCode": {
"id": 8,
"name": "Tax-State",
"_info": {
"taxCode_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/taxCodes/8"
}
},
"billingTerms": {
"id": 1,
"name": "Net 30 days"
},
"billToCompany": {
"id": 250,
"identifier": "comp1 ",
"name": "company1.",
"_info": {
"company_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/250"
}
},
"billingSite": {
"id": 1291,
"name": "company1",
"_info": {
"site_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies"
}
},
"invoiceDeliveryMethod": {
"id": 1,
"name": "Mail"
},
"deletedFlag": false,
"mobileGuid": "1df91371-6d7a-4778-ab81-f3e7761f5211",
"currency": {
"id": 7,
"symbol": "$",
"isoCode": "USD",
"name": "US Dollars",
"_info": {
"currency_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/currencies/7"
}
},
"_info": {
"lastUpdated": "2018-04-02T16:36:05Z",
"updatedBy": "user1",
"dateEntered": "2006-06-21T16:04:59Z",
}
},
{
"id": 250,
"identifier": "company name ",
"name": "company name",
"status": {
"id": 1,
"name": "Active",
"_info": {
"status_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/statuses/1"
}
},
"type": {
"id": 1,
"name": "Client",
"_info": {
"type_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/types/1"
}
},
"addressLine1": "address line 1",
"city": "New York",
"state": "NY",
"zip": "11111",
"country": {
"id": 1,
"name": "United States",
"_info": {
"country_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/countries/1"
}
},
"phoneNumber": "123456789",
"faxNumber": "",
"website": "www.site.com",
"territoryId": 2,
"accountNumber": "",
"dateAcquired": "2006-06-21T04:00:00Z",
"sicCode": {
"id": 1209,
"name": "consulting"
},
"annualRevenue": 0,
"timeZone": {
"id": 1,
"name": "GMT-5/Eastern Time: US & Canada",
"_info": {
"timeZoneSetup_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/system/timeZoneSetups/1"
}
},
"leadFlag": false,
"unsubscribeFlag": false,
"userDefinedField5": "1",
"taxCode": {
"id": 8,
"name": "Tax-State",
"_info": {
"taxCode_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/taxCodes/8"
}
},
"billingTerms": {
"id": 1,
"name": "Net 30 days"
},
"billToCompany": {
"id": 250,
"identifier": "comp1 ",
"name": "company1.",
"_info": {
"company_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/250"
}
},
"billingSite": {
"id": 1291,
"name": "company1",
"_info": {
"site_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies"
}
},
"invoiceDeliveryMethod": {
"id": 1,
"name": "Mail"
},
"deletedFlag": false,
"mobileGuid": "1df91dd371-6d7addd-4778s-ab81-f3e7761f5211",
"currency": {
"id": 7,
"symbol": "$",
"isoCode": "USD",
"name": "US Dollars",
"_info": {
"currency_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/currencies/7"
}
},
"_info": {
"lastUpdated": "2018-04-02T16:36:05Z",
"updatedBy": "user1",
"dateEntered": "2006-06-21T16:04:59Z",
"enteredBy": "CONVERSION",
}
}
]
json_decode() and https://jsonlint.com/ both complain about the comma after the value on lines 95 and 194. Removing them makes it valid json, after which your code works as soon as you remember to quote the key values for the associative array.
I removed the two offending commas in the json and saved as a file, then added the quoting for your key values on the array, and finally removed the HTML table stuff and such (I'm just running it on command line to see output). Should be easy to put back in...
<?php
function get_companies() {
$j = file_get_contents("json.json");
$jd = json_decode($j, true);
return $jd;
}
$accounts = get_companies();
if (!empty($accounts)) {
foreach ($accounts as $account) {
echo "\n".$account['id'] . "
" . $account['name'] . "
" . $account['addressLine1'] . "
" . $account['phoneNumber'] . "
" . $account['website'] . "
" . $account['name']."\n\n";
}
}
?>
According to your comment, it is possible that some properties that you use in your HTML are not part of the JSON you receive. This means you are accessing an array index that is not set, e.g. with $account[website].
I see two solutions for this:
Only output the data if it is set in the array:
echo '<td>'.(isset($account['website']) ? $account['website'] : '').'</td>';
Use a an array with defaults for all the values as base for your $account array and merge them:
$base = [
'website' => 'no website',
'phoneNumber' => '',
];
foreach ($accounts as $account) {
// this will override all elements of $base with them of $account,
// but only if they are present in $account
$account = array_merge($base, $account);
// ... your output here ...
}

How to not display information if it exists in one of two arrays

The situation is I have two arrays that is collecting JSON data via the API :
$players = getAPI("http://xx.xxx.xxx.xx:xxxxx/players.json?apiKey=xxxxxxxxxxxxxxxxxxxxxxxx");
$recents = getAPI("xx.xxx.xxx.xx:xxxxx/recent.json?apiKey=xxxxxxxxxxxxxxxxxxxxxxxx");
The method is getting the contents and decoding the JSON into an array.
For the players array we have this data in an array:
$players
[
{
"id": "76561198033377272",
"name": "PitMonk",
"position": {
"x": -339,
"y": 26,
"z": 191
},
"rotation": 128,
"time": 418310,
"ip": "",
"inventory": {
"main": [],
"belt": [
{
"name": "rock",
"amount": 1,
"blueprint": false,
"condition": 100
},
{
"name": "torch",
"amount": 1,
"blueprint": false,
"condition": 100
}
],
"wear": []
}
},
{
"id": "76561198088638439",
"name": "Pippa",
"position": {
"x": -337,
"y": 25,
"z": 177
},
"rotation": 73,
"time": 419136,
"ip": "",
"inventory": {
"main": [
{
"name": "arrow.wooden",
"amount": 12,
"blueprint": false
},
{
"name": "bow.hunting",
"amount": 1,
"blueprint": false,
"condition": 93
},
{
"name": "blueprint_fragment",
"amount": 25,
"blueprint": false
},
{
"name": "metal.fragments",
"amount": 1366,
"blueprint": false
},
{
"name": "metal.refined",
"amount": 48,
"blueprint": false
},
{
"name": "charcoal",
"amount": 1120,
"blueprint": false
},
{
"name": "lowgradefuel",
"amount": 738,
"blueprint": false
}
],
"belt": [
{
"name": "rock",
"amount": 1,
"blueprint": false,
"condition": 100
},
{
"name": "torch",
"amount": 1,
"blueprint": false,
"condition": 100
},
{
"name": "pickaxe",
"amount": 1,
"blueprint": false,
"condition": 76
},
{
"name": "pickaxe",
"amount": 1,
"blueprint": false,
"condition": 17
},
{
"name": "pickaxe",
"amount": 1,
"blueprint": false,
"condition": 100
},
{
"name": "pickaxe",
"amount": 1,
"blueprint": false,
"condition": 100
}
],
"wear": [
{
"name": "burlap.shirt",
"amount": 1,
"blueprint": false
},
{
"name": "attire.hide.skirt",
"amount": 1,
"blueprint": false
}
]
}
}
]
$recents
[
{
"id": "76561198039206786",
"name": "JakeGroves"
},
{
"id": "76561198088638439",
"name": "Pippa"
},
{
"id": "76561198033377272",
"name": "PitMonk"
},
{
"id": "76561198146864439",
"name": "YepWellDone"
},
{
"id": "76561198164836207",
"name": "Baz"
},
{
"id": "76561198076406281",
"name": "xwalnutx"
},
{
"id": "76561197985716090",
"name": "Darkflame134"
},
{
"id": "76561198263423842",
"name": "XitaikiznerX"
},
{
"id": "76561198129952244",
"name": "NatanGamer"
},
{
"id": "76561198071842055",
"name": "Baha Bey"
}
]
As you can see the players is the people connected, and recents is the total list of people who have connected recently.
I have attempted this:
foreach ($players as $player) {
echo $players->name;
}
echo "</br></br>";
foreach ($recent as $rec) {
if ($rec->name != $player->name) {
echo $rec->name . "</br>";
}
}
and it produces the result:
PitMonk Pippa
JakeGroves
PitMonk
YepWellDone
Baz
xwalnutx
Darkflame134
XitaikiznerX
NatanGamer
Baha Bey
So it is only ignoring 'pippa', I am not sure if it is possible to interact with two arrays as such for unique values?
You are interested in listing all names out of $users which don't exist in $players or $recents, right?
Assuming you are only interested in the name:
// First, let's get a new array with all names from both arrays (can contain dups)
$pcNames = array_map($players + $recents, function($playerObject) {
return $playerObject->name;
});
// Next, let's remove all dups
$pcNames = array_unique($pcNames);
// === At this point you have an array with all names from `$players` and `$recents` ===
// === You may do something else with those, but I'll now create another array with ===
// === all users not in the players/recents lists. ===
// Now let's also get a list of names of users in the `$users` variable
$userNames = array_map($users, function($playerObject) {
return $playerObject->name;
});
// And finally let's get all names which are not in players or recents
$diffNames = array_diff($userNames, $pcNames);
// Let's output those to see whether it worked
var_dump($diffNames);
Of course there are other ways depending on your use case. We could for example extract the names of all three arrays and then just use array_diff with 3 arguments (but then you don't have the $pcArray side product), or if you actually want to compare IDs but print names, we would have to change all the inline functions to extract ID instead of name and further down reference the users array to get the actual name, etc.

how to get data from Google plus json php foreach loop

I'm into a project where I'm trying to get information from a json response (Again), that I got from google+.
I need to return an array after populating it with some information from the json response.
The [modified] json response is thus:
{
"items": [
{
"kind": "plus#activity",
"etag": "\"gLJf7Ldsgfsdgsgsf9ES9mEc/LFcp0tW7Ffgfsdgdf4Yfgdff3Z8\"",
"title": "first title",
"published": "2015-08-13T12:23:36.316Z",
"updated": "2015-08-13T12:23:36.316Z",
"id": "z12njfgogxirwdsoihosdhgjsdghusdn",
"url": "https://plus.google.com/+ABCBEHGHIJ/posts/8QZBMRjHVMF",
"actor": {
"id": "210973863758690009009",
"displayName": "a name",
"url": "https://plus.google.com/210973863758690009009",
"image": {
"url": "https://lh4.googleusercontent.com/-ihfjbhjbsduj/AAAfgdagAAAI/AAAgdfgfdAPQ/oBXvfgdgdf1aeLQ/photo.jpg?sz=50"
},
"verification": {
"adHocVerified": "UNKNOWN_VERIFICATION_STATUS"
}
},
"verb": "post",
"object": {
"objectType": "note",
"actor": {
"verification": {
"adHocVerified": "UNKNOWN_VERIFICATION_STATUS"
}
},
"content": " \u003ca rel=\"nofollow\" class=\"ot-hashtag\" href=\"https://plus.google.com/s/%oko\"\u003es\u003c/a\u003e\ufeff",
"url": "https://plus.google.com/+ABCBEHGHIJ/posts/8QZiUyuyuobsvASKKHVMF",
"replies": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/z12ZiUyuyuobsvASKKcxqnn/comments"
},
"plusoners": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/z12njfgogZiUyuyuobsvASKKcxqnn/people/plusoners"
},
"resharers": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/z12njfZiUyuyuobsvASKKqnn/people/resharers"
},
"attachments": [
{
"objectType": "photo",
"displayName": "Photo 1",
"id": "210973863758690009009.6618960307328673257603073286732572860914",
"content": "123",
"url": "https://plus.google.com/photos/21096189603073286732572860914009/albums/616189603073286732572860914457/66189603073286732572860914385860914",
"image": {
"url": "https://lh5.googleusercontent.com/-2dgjFRZCII8/VcyMOOCHLTI/BAAHYGHDSJH/0XtjUD1perY/w506-h750/11017878_1655020691394612_1878283374465430482_n.jpg",
"type": "image/jpeg"
},
"fullImage": {
"url": "https://lh5.googleusercontent.com/-2dgjFRSDSDD8/VcyMSDSDSI/BAAHYGHDSJHDSIKA/0XtjIUYDIGIDGerY/11017878_1655020DSDKHSJ612_1878283374SDSDSD30482_n.jpg",
"type": "image/jpeg",
"height": 540,
"width": 540
}
}
]
},
"provider": {
"title": "Google+"
},
"access": {
"kind": "plus#acl",
"description": "Public",
"items": [
{
"type": "public"
}
]
}
},
{
"kind": "plus#activity",
"etag": "\"gLJf7LwN3wOpLHXk4IeQ9ES9mEc/TUMFP7Wc8QTGatBg1vGSEbjPPDE\"",
"title": "second title",
"published": "2015-08-13T11:57:49.262Z",
"updated": "2015-08-13T11:57:49.262Z",
"id": "z1iohyfsdugsjhockob0n232vjiz5xancxqnn",
"url": "https://plus.google.com/+ABCBEHGHIJ/posts/4DVBTreNkyA",
"actor": {
"id": "210973863758690009009",
"displayName": "a name",
"url": "https://plus.google.com/210973863758690009009",
"image": {
"url": "https://lh4.googleusercontent.com/-ihfjbhjbsduj/BAAHYGHDSJH/BAAHYGHDSJH/oBXvDSDASAeLQ/photo.jpg?sz=50"
},
"verification": {
"adHocVerified": "UNKNOWN_VERIFICATION_STATUS"
}
},
"verb": "post",
"object": {
"objectType": "note",
"actor": {
"verification": {
"adHocVerified": "UNKNOWN_VERIFICATION_STATUS"
}
},
"content": "07012345678\ufeff",
"url": "https://plus.google.com/+ABCBEHGHIJ/posts/4DVBiodjjdmknaayA",
"replies": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/pfjknsfubsnjbsb0n232vjiz5xancxqnn/comments"
},
"plusoners": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/pfjknsfubsnjbsb0n232vjiz5xancxqnn/people/plusoners"
},
"resharers": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/pfjknsfubsnjbsb0n232vjiz5xancxqnn/people/resharers"
},
"attachments": [
{
"objectType": "photo",
"displayName": "Photo 2",
"id": "210973863758690009009.6837572367923789379",
"content": "456",
"url": "https://plus.google.com/photos/210973863758690009009/albums/6947862082892799114865/69843868408496745035842",
"image": {
"url": "https://lh3.googleusercontent.com/-Tvib82iMpsk/VcyGKh3UGAI/ADLJSKNSHJBSDNB AAQM/cyhYX3SifDY/w506-h750/1024-2006_1011_093752.jpg",
"type": "image/jpeg"
},
"fullImage": {
"url": "https://lh3.googleusercontent.com/-Tvijihjsdbnjgsdupsk/VcfjhjfsbjgsugAI/ApkdlnsdjkbjsdAQM/cyhYX3SifDY/w1024-h768/1024-2006_1011_093752.jpg",
"type": "image/jpeg",
"height": 768,
"width": 1024
}
}
]
},
"provider": {
"title": "Google+"
},
"access": {
"kind": "plus#acl",
"description": "Public",
"items": [
{
"type": "public"
}
]
}
},
{
"kind": "plus#activity",
"etag": "\"gLJfnjsdjnvdsvhsdIeQ9EpoifkjnfmEc/P4ihjsadiadakhlbhvdshvfXan4\"",
"title": "third title",
"published": "2015-08-12T22:57:22.010Z",
"updated": "2015-08-12T22:57:22.010Z",
"url": "https://plus.google.com/+ABCBEHGHIJ/posts/iiuhfdjhfidpnbvcW",
"actor": {
"displayName": "a name",
"url": "https://plus.google.com/210973863758690009009",
"image": {
"url": "https://lh4.googleusercontent.com/-ihfjbhjbsduj/BAJDHJDSIDKAI/PODSIOUSDIKAAPQ/oBXvlp1aeLQ/photo.jpg?sz=50"
},
"verification": {
"adHocVerified": "UNKNOWN_VERIFICATION_STATUS"
}
},
"verb": "post",
"object": {
"objectType": "note",
"actor": {
"verification": {
"adHocVerified": "UNKNOWN_VERIFICATION_STATUS"
}
},
"content": " \u003ca rel=\"nofollow\" class=\"ot-hashtag\" href=\"https://plus.google.com/s/IUYDHJDSUGDSHGY\"\u003eIUYDHJDSUGDSHGY\u003c/a\u003e \ufeff",
"url": "https://plus.google.com/+ABCBEHGHIJ/posts/iukdjkdowqvcW",
"replies": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/uihfjbsjkbsfdnfffdfdpokrouh3quig/comments"
},
"plusoners": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/uihfjbsjkbsfdnfffdfdpokrouh3quig/people/plusoners"
},
"resharers": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/uihfjbsjkbsfdnfffdfdpokrouh3quig/people/resharers"
},
"attachments": [
{
"objectType": "photo",
"displayName": "Photo 3",
"content": "789",
"url": "https://plus.google.com/photos/210973863758690009009/albums/6182262671805531297/618654563857564534922",
"image": {
"url": "https://lh3.googleusercontent.com/-uihfjbsdhgsdilop/VcvPJmJ0bUI/wERRDFFAAAAN8/X6J9fHJVBFDVSFVSak/w506-h750/PicsArt_1438914428134.jpg",
"type": "image/jpeg"
},
"fullImage": {
"url": "https://lh3.googleusercontent.com/-uihfjbsdhgsdilop/VcvPJmJ0bUI/wERRDFFAAAAN8/XyghFGF2TgBak/w562-h562/PicsArt_1438914428134.jpg",
"type": "image/jpeg",
"height": 562,
"width": 562
}
}
]
},
"provider": {
"title": "Google+"
},
"access": {
"kind": "plus#acl",
"description": "Public",
"items": [
{
"type": "public"
}
]
}
},
{
"kind": "plus#activity",
"etag": "\"gLJioyuhgdugudsgugc/UGHAoodpuskhjhgsdjdbY0\"",
"title": "fourth title",
"published": "2011-09-26T17:13:14.309Z",
"updated": "2011-09-26T17:13:14.309Z",
"id": "z12odlnbgmavzdh4k04cgfhxvwrouh3quig",
"url": "https://plus.google.com/+ABCBEHGHIJ/posts/R9zieiuhdjghdgBFu",
"actor": {
"id": "210973863758690009009",
"displayName": "a name",
"url": "https://plus.google.com/210973863758690009009",
"image": {
"url": "https://lh4.googleusercontent.com/-ihfjbhjbsduj/AKHDSJHSDGAAI/AUIDHIJGDSHGHAPQ/oBXvlp1aeLQ/photo.jpg?sz=50"
},
"verification": {
"adHocVerified": "UNKNOWN_VERIFICATION_STATUS"
}
},
"verb": "post",
"object": {
"objectType": "note",
"actor": {
"verification": {
"adHocVerified": "UNKNOWN_VERIFICATION_STATUS"
}
},
"content": "UIHUIGG FJGF GU",
"url": "https://plus.google.com/+ABCBEHGHIJ/posts/R9zStuw9BFu",
"replies": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/oilzdh4k04cgpooiyuewfouh3quig/comments"
},
"plusoners": {
"totalItems": 1,
"selfLink": "https://www.googleapis.com/plus/v1/activities/oilzdh4k04cgpooiyuewfouh3quig/people/plusoners"
},
"resharers": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/zkjhsdsfgiooi;oilzdh4k04cgpooiyuewfouh3quig/people/resharers"
}
},
"provider": {
"title": "Google+"
},
"access": {
"kind": "plus#acl",
"description": "Public",
"items": [
{
"type": "public"
}
]
}
},
{
"kind": "plus#activity",
"etag": "\"oilzdh4k04cgpooiyuewfouh3quig/oilzdh4k04cgpooiyuewfouh3quig\"",
"title": "fifth title",
"published": "2011-09-26T17:09:23.712Z",
"updated": "2011-09-26T17:09:23.712Z",
"id": "z13msxkxfnjjvp04p04cgfhxvwrouh3quig",
"url": "https://plus.google.com/+ABCBEHGHIJ/posts/RvXF5ufy23n",
"actor": {
"id": "210973863758690009009",
"displayName": "a name",
"url": "https://plus.google.com/210973863758690009009",
"image": {
"url": "https://lh4.googleusercontent.com/-ihfjbhjbsduj/AAAAAAAAAAI/AAAAAAAAAPQ/oilzdh4k04cgpooiyuewfouh3quig/photo.jpg?sz=50"
},
"verification": {
"adHocVerified": "UNKNOWN_VERIFICATION_STATUS"
}
},
"verb": "post",
"object": {
"objectType": "note",
"actor": {
"verification": {
"adHocVerified": "UNKNOWN_VERIFICATION_STATUS"
}
},
"content": "witout 'ME' it's jst AWESO....\ufeff",
"url": "https://plus.google.com/+ABCBEHGHIJ/posts/RvXF5ufy23n",
"replies": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/oilzdh4k04cgpooiyuewfouh3quig/comments"
},
"plusoners": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/oilzdh4k04cgpooiyuewfouh3quig/people/plusoners"
},
"resharers": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/gLJfoiojkdwjkshdikhdhisEc/people/resharers"
}
},
"provider": {
"title": "Google+"
},
"access": {
"kind": "plus#acl",
"description": "Public",
"items": [
{
"type": "public"
}
]
}
},
{
"kind": "plus#activity",
"etag": "\"gLJfoiojkdwjkshdikhdhisEc/gLJfoiojkdwjkshdikhdhisEc\"",
"title": "sixth title",
"published": "2011-09-26T17:07:05.897Z",
"updated": "2011-09-26T17:07:05.897Z",
"id": "gLJfoiojkdwjkshdikhdhisEc",
"url": "https://plus.google.com/+ABCBEHGHIJ/posts/gLJfoiojkdwjkshdikhdhisEc",
"actor": {
"id": "210973863758690009009",
"displayName": "a name",
"url": "https://plus.google.com/210973863758690009009",
"image": {
"url": "https://lh4.googleusercontent.com/-ihfjbhjbsduj/AASKJAKHJGASQAPQ/AASKJAKHJGASQAPQ/gLJfoiojkdwjkshdikhdhisEc/photo.jpg?sz=50"
},
"verification": {
"adHocVerified": "UNKNOWN_VERIFICATION_STATUS"
}
},
"verb": "post",
"object": {
"objectType": "note",
"actor": {
"verification": {
"adHocVerified": "UNKNOWN_VERIFICATION_STATUS"
}
},
"content": "dere's an xception 2 evry rule, xcept dis 1..\ufeff",
"url": "https://plus.google.com/+ABCBEHGHIJ/posts/N6QTZt2XvSR",
"replies": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/gLJfoiojkdwjkshdikhdhisEc/comments"
},
"plusoners": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/gLJfoiojkdwjkshdikhdhisEc/people/plusoners"
},
"resharers": {
"totalItems": 0,
"selfLink": "https://www.googleapis.com/plus/v1/activities/gLJfoiojkdwjkshdikhdhisEc/people/resharers"
}
},
"provider": {
"title": "Google+"
},
"access": {
"kind": "plus#acl",
"description": "Public",
"items": [
{
"type": "public"
}
]
}
}
]
}
this is what I'm doing:
function google_pluss() {
$file_dir = strtolower(realpath(APPPATH . '..' . DIRECTORY_SEPARATOR . 'assets'));
$json_file = $file_dir . DIRECTORY_SEPARATOR . 'stackoverflow' . '.json'; // I have the file locally...
$json_data = json_decode(file_get_contents($json_file));
$data = array();
if (isset($json_data)) {
$x = 0;
foreach ($json_data->items as $item) {
if (isset($item->object->attachments)) {
foreach ($item->object->attachments as $attachment) {
$data['number'][$x] = $attachment->content;
$data['image'][$x] = $attachment->fullImage->url;
}
$data['title'][$x] = $item->title;
$x++;
}
}
}
print_r($data);
}
this is the output I get:
Array
(
[number] => Array
(
[0] => 123
[1] => 456
[2] => 789
)
[image] => Array
(
[0] => https://lh5.googleusercontent.com/-2dgjFRSDSDD8/VcyMSDSDSI/BAAHYGHDSJHDSIKA/0XtjIUYDIGIDGerY/11017878_1655020DSDKHSJ612_1878283374SDSDSD30482_n.jpg
[1] => https://lh3.googleusercontent.com/-Tvijihjsdbnjgsdupsk/VcfjhjfsbjgsugAI/ApkdlnsdjkbjsdAQM/cyhYX3SifDY/w1024-h768/1024-2006_1011_093752.jpg
[2] => https://lh3.googleusercontent.com/-uihfjbsdhgsdilop/VcvPJmJ0bUI/wERRDFFAAAAN8/XyghFGF2TgBak/w562-h562/PicsArt_1438914428134.jpg
)
[title] => Array
(
[0] => first title
[1] => second title
[2] => third title
)
)
But, this is the output I actually need:
Array
(
[0] => Array
(
[number] => 123
[image] => https://lh5.googleusercontent.com/-2dgjFRSDSDD8/VcyMSDSDSI/BAAHYGHDSJHDSIKA/0XtjIUYDIGIDGerY/11017878_1655020DSDKHSJ612_1878283374SDSDSD30482_n.jpg
[title] => first title
)
[1] => Array
(
[number] => 456
[image] => https://lh3.googleusercontent.com/-Tvijihjsdbnjgsdupsk/VcfjhjfsbjgsugAI/ApkdlnsdjkbjsdAQM/cyhYX3SifDY/w1024-h768/1024-2006_1011_093752.jpg
[title] => second title
)
[2] => Array
(
[number] => 789
[image] => https://lh3.googleusercontent.com/-uihfjbsdhgsdilop/VcvPJmJ0bUI/wERRDFFAAAAN8/XyghFGF2TgBak/w562-h562/PicsArt_1438914428134.jpg
[title] => third title
)
)
I'd really appreciate if someone shows me how to achieve this, thank you.
btw, I'm using the $x variable and incrementing it, to stop the loop where the array doesn't contain attachments. I'd be glad too, if shown how to do this neater.
At first glance, I would say change
foreach ($item->object->attachments as $attachment) {
$data['number'][$x] = $attachment->content;
$data['image'][$x] = $attachment->fullImage->url;
}
to
foreach ($item->object->attachments as $attachment) {
$data[$x]['number'] = $attachment->content;
$data[$x]['image'] = $attachment->fullImage->url;
}

Categories