PHP Extracting a certain part of JSON string where username equals - php

I was wondering how to extract only a certain part from a JSON String:
[
{
"ID": "132",
"countrycode": "DE",
"USERNAME": "CRC Titan2000",
"Nickname": "^7[6S] ^1Titan",
"Money": "550111",
"Distance": "105692714",
"Trip": "370839",
"Bonus": "223",
"Last Car": "RB4",
"Last Position": "The Hills",
"Server": "^7One"
},
{
"ID": "1634",
"countrycode": "ES",
"USERNAME": "lobocop",
"Nickname": "^4Leo ^1Messi",
"Money": "12816",
"Distance": "17091463",
"Trip": "25682",
"Bonus": "29",
"Last Car": "MRT",
"Last Position": "Bridge East",
"Server": "^7One"
},
{
"ID": "4240",
"countrycode": "GB",
"USERNAME": "Smacky",
"Nickname": "^7^d^6o^7^s",
"Money": "-532",
"Distance": "1987579",
"Trip": "7738",
"Bonus": "51",
"Last Car": "RB4",
"Last Position": "The Hills",
"Server": "^7One"
},
{
"ID": "5467",
"countrycode": "TR",
"USERNAME": "excaTR",
"Nickname": "^1Furkan^7Tr",
"Money": "7363",
"Distance": "17064283",
"Trip": "15747",
"Bonus": "31",
"Last Car": "RB4",
"Last Position": "Bridge East",
"Server": "^7One"
}
]
I only want to pull the "Last Position" of the "USERNAME" excaTR, but ignore all the others. Sort of like a MySQL query, where I want to echo the last position WHERE username='excaTR', but instead for PHP and JSON.
This is the code that I tried, but it didn't work
$json_stats = file_get_contents('<JSON string here>');
$stats_data = json_decode($json_stats, true);
foreach ($stats_data as $_SESSION['username'] => $location){
echo $location['Last Position'];
}

You are not using foreach as it should be.
Have a look at your JSON, you have an array of objects.
So you have to iterate over you array, and check your object values.
By the way, in my answer, I use json_decode( ,false) to force result as a multidimensional array, matter of taste only.
$json_stats = file_get_contents('<JSON string here>');
$stats_data = json_decode($json_stats, false);
foreach ($stats_data as $array) {
if ($array['USERNAME'] == 'excaTR') {
echo $array['Last Position'];
}
}

Related

php json foreach string value

I have a JSON file which contains some movie data:
[{
"title": "Bad Company",
"desc": "------------------------",
"rating": "6.0",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اكشن"
}, {
"title": "The Pinch",
"desc": "------------------------",
"rating": "6.1",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اكشن , جريمه"
}, {
"title": "Catskill Park",
"desc": "------------------------",
"rating": "6.2",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "خيال علمي , رعب"
}, {
"title": "Klippers",
"desc": "------------------------",
"rating": "5.3",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اثاره , اكشن"
}, {
"title": "Psycho",
"desc": "------------------------",
"rating": "5.6",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اثاره , دراما"
}]
I need to add all titles to a drop down menu, and when a user selects an item from the menu show the desc, image and category.
by php
Can anyone help me please?
my traying code
$url = 'http://localhost/ar.json';
$xx = json_decode(file_get_contents($url));
$data = json_decode($xx, true);
$search='title';
foreach($data['meta_data'] as $d){
if($d['key']==$search){
$found=$d['value'];
break;
}
}
echo $found?$found:"$search not found";
Assuming the structure, which you do not fully how us, is correct.
Use the key and value method of a foreach like this
$url = 'http://localhost/ar.json';
$xx = json_decode(file_get_contents($url));
$data = json_decode($xx, true);
$search='title';
$found = false;
foreach($data['meta_data'] as $key => $val){
if($key == $search){
$found = $val;
break;
}
}
echo $found ? $found : "$search not found";

Jotform: Parse returned data issue

I'm trying to parse data returned by the Jotform API.
I'm successfully echoing the data but I'm also getting unnecessary additional lines of text.
My PHP code is:
include "JotForm.php";
$jotformAPI = new JotForm("myapikey");
$submissions = $jotformAPI->getFormSubmissions("myformid");
var_dump($submissions );
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
foreach ($detail as $d) {
echo $d[1]['answer']['first'] . '<br>';
}
}
result of var_dump($submissions );
{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}],
}
And here is the result I'm getting:
1
0
0
0
C
0
LeBron
I had to repair your invalid json string...
Code: (Demo)
$json = '{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}}]
}';
foreach (json_decode($json, true)['content'] as $set) {
echo "{$set['answers'][1]['answer']['first']} {$set['answers'][1]['answer']['last']}\n";
}
Output:
LeBron James
I'm a little fuzzy on the action of the jot functions, but maybe it's supposed to be like this:
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
echo $detail['answers'][1]['answer']['first'] . '<br>';
}

Creating a multidimensional array from json in php

I have a json file with a lot of records with fields for date, time and isApproved. What I am trying to do is to create a json rray that has dates for all the records that are approved. And the dates have all the hours that are booked for the current date.
So from this... :
[{"fullName":"Jojn Petkobsky","userName":"user1","phone":"12415455","email":"ees#asd.com"date":"11\/16\/2016","time":"1pm ","reason":"ReaReasonReaeason","isApproved":0,"label":"warning","status":"Approved"},{"fullName":"Zoltan Heinkelman","userName":"user2","phone":"12415455","email":"ees#asdd.com"date":"11\/16\/2016","time":"2pm ","reason":"ReaReasonReaeason","isApproved":1,"label":"warning","status":"Approved"}{"fullName":"Jojn Petkobsky","userName":"user1","phone":"12415455","email":"ees#asd.com"date":"11\/16\/2016","time":"1pm ","reason":"ReaReasonReaeason","isApproved":1,"label":"warning","status":"Approved"},{"fullName":"Frank Heinkelman","userName":"user3","phone":"12415455","email":"ees#asddd.com"date":"10\/11\/2016","time":"2pm ","reason":"ReaReasonReaeason","isApproved":1,"label":"warning","status":"Approved"}]
...i can have something like this, so i can have all the booked hours for a given date.
{"12/11/16"😞
{"time" :"10am"},
{"time" :"1pm"},
{"time" :"5pm"}
]
"12/10/16"😞
{"time" :"9am"}
]
}
I tried with something like this, but couldn't really finish it :
$string = file_get_contents("appointments.json");
$json_a = json_decode($string, true);
$date;
$datesTimes = array();
foreach($json_a as $json_r){
if ($json_r['isApproved']==1) {
$date = $json_r['date'];
//another foreach?
}
}
Any help will be appreciated!
As I mentioned in the comments, your JSON is NOT valid so I have fixed it to a point to show how it can be done.
//Fixed JSON as much as I could to show in example.
$json = '
[
{
"fullName": "Jojn Petkobsky",
"userName": "user1",
"phone": "12415455",
"email": "ees#asd.com",
"date": "11\/16\/2016",
"time": "1 pm",
"reason": "ReaReasonReaeason",
"isApproved": "0",
"label": "warning",
"status": "Approved"
},
{
"fullName": "Kitson88",
"userName": "user2",
"phone": "122323325",
"email": "eadasds#asasdasdd.com",
"date": "11\/16\/2016",
"time": "12 pm",
"reason": "ReaReasonReaeason",
"isApproved": "0",
"label": "warning",
"status": "Approved"
},
{
"fullName": "Jamie",
"userName": "user2",
"phone": "122323325",
"email": "eadasds#asasdasdd.com",
"date": "12\/16\/2016",
"time": "8 pm",
"reason": "ReaReasonReaeason",
"isApproved": "0",
"label": "warning",
"status": "Approved"
}
]
';
$array = json_decode($json, true);
//This will be you rnew Array for holding the needed data.
$approved = [];
foreach ($array as $value) {
if ($value['status'] === 'Approved') { //Any check really which will validate Approved
if (array_key_exists($value['date'], $approved)) { //Check if key exists note** will only work on 1D Array
array_push($approved[$value['date']], $value['time']); //If so, then append
} else { //If not, then create it and add value
$approved += [$value['date'] => [$value['time']]];
}
}
}
//Encode back to JSON
$newJson = json_encode($approved);
Output as JSON
{
"11\/16\/2016": ["1 pm", "12 pm"],
"12\/16\/2016": ["8 pm"]
}
http://php.net/manual/en/function.array-key-exists.php
http://php.net/manual/en/function.array-push.php

get value in multi dimensional array using php

I'd like to get the value of array from multi dimensional array. Let say I have json response from API which I decoded using json_decode() function in php and I want using loop to iterate the data.
$string = $response;
$json_a = json_decode($string, true);
foreach($json_a['withdrawals'] as $item) {
echo $item['withdrawalId']['amount']['currencyCode']. '<br/>';
echo $item['withdrawalId']['terminal']['tid']. '<br/>';
echo $item['withdrawalId']['user']['mid']. '<br/>';
echo $item['servicefee']['masterMerchant']['name']. '<br/>';
echo $item['servicefee']['masterMerchant']['address']['address1']. '<br/>';
}
}
print_r($json_a);
and here's the print out of arrays.
{
"limit": 1,
"offset": 0,
"totalTransactionsCount": 5040,
"acceptedTotalTransactionsCount": 4428,
"acceptedTotalTransactionsValue": 2438928.04,
"rejectedTotalTransactionsCount": 612,
"rejectedTotalTransactionsValue": 499294.04,
"withdrawals": [
{
"withdrawalId": "764353634316",
"status": "approval",
"dateTime": "2016-04-28T09:31:38.145Z",
"localDateTime": "2016-04-28 17:31:38",
"accountType": "CURRENT",
"additionalInfo": "approved",
"batch": "000029",
"smscount": 0
"amount": {
"currencyCode": "EUR",
"value": "399.99"
},
"terminal": {
"tid": "88133332",
"serialNumber": "45435435"
},
"user": {
"name": "John Doe",
"email": "jmeter#joe.com",
"phoneNumber": "546546546",
"role": "OPERATOR",
"subMerchant": {
"name": "Submerchant XXY",
"mid": "MID0000"
"serviceFee": {
"name": "rsf",
"merchantFee": "10.0"
},
"masterMerchant": {
"name": "Master Merchant",
"address": {
"address1": "Mainstreet",
"city": "Cork",
"postcode": "Cork",
"country": {
"countryName": "Philippines",
"countryCode": "PH",
"currencyName": "Philippines Peso",
"currencyCode": "PHP",
}
}
},
"address": {
"address1": "Mainstreet",
"city": "Cork",
"postcode": "Cork",
"country": {
"countryName": "Philippines",
"countryCode": "PH",
"currencyName": "Philippines Peso",
"currencyCode": "PHP",
}
}
}
}
}]}
Write it like this:-
$string = $response;
$json_a = json_decode($string, true);
foreach($json_a['withdrawals'] as $item) {
echo $item['withdrawalId']. '<br/>';
echo $item['amount']['currencyCode']. '<br/>';
echo $item['terminal']['tid']. '<br/>';
echo $item['user']['mid']. '<br/>';
echo $item['user']['masterMerchant']['name']. '<br/>';
echo $item['user']['masterMerchant']['address']['address1']. '<br/>';
}
}
print_r($json_a);

Reading a large JSON from Facebook

How can I read several values with the same name from a JSON from Facebook, when I use this code:
$urlamandar = 'https://graph.facebook.com/'.$user."?access_token=".$access_token;
$content = file_get_contents($urlamandar);
$obj = json_decode($content, true);
$obj = json_decode($content);
It displays this:
{
"id": "XXXXXXXX",
"name": "Ricardo Capistran",
"first_name": "Ricardo",
"last_name": "Capistran",
"gender": "male",
"locale": "es_MX",
"username": "richycapy"
}
And since because there is only one ID, one NAME, one USERNAME, etc, Its quite simple place them in vars like so:
$fbuserid = $obj->{'id'};
$fbname = $obj->{'name'};
$fbusername = $obj->{'username'};
$fbemail = $obj->{'email'};
$fbbirthday = $obj->{'birthday'};
But when it comes to larger files like this code:
$urlamandar = 'https://graph.facebook.com/'.$user.'/albums?access_token='.$access_token;
Its displays a way bigger array like so:
{
"data": [
{
"id": "10150732237818223",
"from": {
"name": "Ricardo Capistran",
"id": "XXXXXXX"
},
"name": "EnterateNorte.com Photos",
"link": "https://www.facebook.com/album.php?fbid=10150732237818223&id=743158222&aid=457026",
"privacy": "custom",
"count": 31,
"type": "app",
"created_time": "2012-03-11T02:44:42+0000",
"updated_time": "2014-01-07T03:13:24+0000",
"can_upload": false
},
{
"id": "440168313222",
"from": {
"name": "Ricardo Capistran",
"id": "743158222"
},
"name": "Timeline Photos",
"link": "https://www.facebook.com/album.php?fbid=440168313222&id=743158222&aid=220377",
"cover_photo": "10151730849598223",
"privacy": "everyone",
"count": 175,
"type": "wall",
"created_time": "2010-06-30T22:38:45+0000",
"updated_time": "2014-01-01T02:09:11+0000",
"can_upload": false
},
{
"id": "10150797320378223",
"from": {
"name": "Ricardo Capistran",
"id": "743158222"
},
"name": "Instagram Photos",
"link": "https://www.facebook.com/album.php?fbid=10150797320378223&id=743158222&aid=466555",
"cover_photo": "10151695050098223",
"privacy": "friends",
"count": 37,
"type": "app",
"created_time": "2012-04-09T23:50:08+0000",
"updated_time": "2013-12-29T08:29:15+0000",
"can_upload": false
}
],
"paging": {
"cursors": {
"after": "NDM1NjY5NjI4MjIy",
"before": "MTAxNTA3MzIyMzc4MTgyMjM="
},
"next": "https://graph.facebook.com/*my_id*/albums?access_token=*access_token*&limit=25&after=NDM1NjY5NjI4MjIy"
}
}
And I would need the “name” and “id” off all the albums, so then I can repeat this same procedure with the containing pictures
Obviously it has way more albums, I just cut it after 3 just to explain my self…
Is there a way to place them in vars? With a php “for each” some how
Thanks!
You can do something like
$obj = json_decode($content, true);
$array_album = array();
foreach($obj['data'] as $key=>$val){
$array_album[] = array("id"=>$val["id"],"name"=>$val["name"]);
echo "ID : ".$val["id"]. " NAME : ".$val["name"] ;
echo "<br />";
}
print_r($array_album); // This will have all the id and names
If you dont want to store in array then the names and id will appear in the above loop and you can do whatever you want with those values. Or use the array $array_album and loop through if you want to use it later.

Categories