I have a field in a json object I am trying to do a pattern match for but I cannot seem to reach the second layer of the object.
JSON:
{
"1680488": {
"SUBID": "1680488",
"os": "FreeBSD 10 x64",
"ram": "2048 MB",
"disk": "Virtual 40 GB",
"main_ip": "107.191.60.48",
"vcpu_count": "2",
"location": "Tokyo",
"DCID": "25",
"default_password": "4",
"date_created": "2015-02-06 02:27:22",
"pending_charges": 7.61,
"status": "active",
"cost_per_month": "18.00",
"current_bandwidth_gb": 2.706,
"allowed_bandwidth_gb": "600",
"netmask_v4": "255.255.254.0",
"gateway_v4": "107.191.60.1",
"power_status": "running",
"VPSPLANID": "8",
"v6_network": "2001:19f0:7000:8945::",
"v6_main_ip": "2001:19f0:7000:8945::64",
"v6_network_size": "64",
"label": "Freetoo",
"internal_ip": "",
"kvm_url": "https://my.vultr.com/subs/vps/novnc/api.php?data=",
"auto_backups": "yes"
},
"1685960": {
"SUBID": "1685960",
"os": "FreeBSD 10 x64",
"ram": "768 MB",
"disk": "Virtual 15 GB",
"main_ip": "108.61.190.64",
"vcpu_count": "1",
"location": "Frankfurt",
"DCID": "9",
"default_password": "1",
"date_created": "2015-02-09 00:22:42",
"pending_charges": 2.54,
"status": "active",
"cost_per_month": "6.00",
"current_bandwidth_gb": 0.612,
"allowed_bandwidth_gb": "1000",
"netmask_v4": "255.255.255.0",
"gateway_v4": "108.61.190.1",
"power_status": "running",
"VPSPLANID": "29",
"v6_network": "2001:19f0:6c00:8141::",
"v6_main_ip": "2001:19f0:6c00:8141::64",
"v6_network_size": "64",
"label": "",
"internal_ip": "",
"kvm_url": "https://my.vultr.com/subs/vps/novnc/api.php?data=",
"auto_backups": "yes"
},
"1694100": {
"SUBID": "1694100",
"os": "FreeBSD 10 x64",
"ram": "768 MB",
"disk": "Virtual 15 GB",
"main_ip": "108.61.175.20",
"vcpu_count": "1",
"location": "London",
"DCID": "8",
"default_password": "9",
"date_created": "2015-02-12 13:21:33",
"pending_charges": 2.54,
"status": "active",
"cost_per_month": "6.00",
"current_bandwidth_gb": 1.51,
"allowed_bandwidth_gb": "1000",
"netmask_v4": "255.255.255.0",
"gateway_v4": "108.61.175.1",
"power_status": "running",
"VPSPLANID": "29",
"v6_network": "2001:19f0:7400:84c6::",
"v6_main_ip": "2001:19f0:7400:84c6::64",
"v6_network_size": "64",
"label": "",
"internal_ip": "",
"kvm_url": "https://my.vultr.com/subs/vps/novnc/api.php?data=",
"auto_backups": "yes"
},
"1847630": {
"SUBID": "1847630",
"os": "FreeBSD 10 x64",
"ram": "768 MB",
"disk": "Virtual 15 GB",
"main_ip": "108.61.169.203",
"vcpu_count": "1",
"location": "Sydney",
"DCID": "19",
"default_password": "ye!5",
"date_created": "2015-04-12 05:57:47",
"pending_charges": 0.11,
"status": "active",
"cost_per_month": "5.00",
"current_bandwidth_gb": 2.43,
"allowed_bandwidth_gb": "200",
"netmask_v4": "255.255.254.0",
"gateway_v4": "108.61.168.1",
"power_status": "stopped",
"VPSPLANID": "31",
"v6_network": "2001:19f0:5800:8561::",
"v6_main_ip": "2001:19f0:5800:8561::64",
"v6_network_size": "64",
"label": "sydney temp",
"internal_ip": "",
"kvm_url": "https://my.vultr.com/subs/vps/novnc/api.php?data=",
"auto_backups": "no"
}
}
Code:
function getlist(){
$list_output = file_get_contents('https://api.vultr.com/v1/server/list?api_key=UY');
return $list_output;
}
//var_dump($server_output);
echo '<br><br><br><br>';
$output = getlist();
$decoded = json_decode($output, true);
//var_dump($decoded);
foreach ($decoded as $value) {
//echo $value['SUBID'];
foreach ($value['SUBID'] as $piece) {
echo '<br>';
//var_dump($value);
echo $piece;
}
}
but any attempt to reach that second layer array fails with;
Warning: Invalid argument supplied for foreach() in /home/comm/www/mkdomain/vultr-mkvps.php on line 14
or similar.
How do I access the field 'labels' n the json viewer above and pattern match for Freetoo?
That is the exact object I am trying to reach.
No, once inside the foreach there is no more depth to iterate, its just strings after that (based on the dump), its not iterable anymore, so that foreach inside is useless. Just access the strings indices and make your desired condition:
foreach($decoded as $value) {
$id = $value['SUBID']; // string not array
$label = $value['label']; // string
if($label === 'Freetoo') {
// do something
echo $id; // and others that you have to do
}
}
Sample Output
If you're insistent of having another superfluous foreach inside, point to the current batch array, not the string.
foreach($decoded as $value) {
foreach($value as $key => $piece) { // point to `$value` the array, not `$value['SUBID']` (string)
if($key === 'label' && $piece === 'Freetoo') {
echo $value['SUBID'];
}
}
}
I hope this is you want..sample code
$output = json_decode($jsoninput,true);
foreach($output as $subid=>$row){
echo $subid;
foreach ($row as $piece) {
echo '<br>';
//var_dump($row);
echo $piece;
}
}
Related
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>';
}
I have a json response like this:
{
"status": 200,
"msg": "OK",
"result": {
"folders": [
{
"id": "3812454",
"name": ".subtitles"
},
{
"id": "3812455",
"name": ".videothumb"
}
],
"files": [
{
"name": "Angamaly Diaries HD.MP4.mp4",
"cblock": null,
"sha1": "fcc2c99f2db6e3e8a700c3247206a1c2148e14cb",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "713544705",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "PjUv5IYA2J8"
},
{
"name": "Take Off 2017.MP4.mp4",
"cblock": null,
"sha1": "2fe7fb4d45322a085d41239d6429d1cc8e94e2ce",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "954148848",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "BIBcjWqF0_I"
},
{
"name": "Rangoon 2017 Tamil.MP4.mp4",
"cblock": null,
"sha1": "c685e7c11636982860ae7f34b671a20fc746feee",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "779899588",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "00D7GzP6mls"
},
{
"name": "The Zookeeper’s Wife 2017.MP4.mp4.mp4",
"cblock": null,
"sha1": "a143faafbd8a6eaf2276f25cd642ac3019d71ffc",
"folderid": "3812453",
"upload_at": "1510256266",
"status": "active",
"size": "550126461",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "bwUhqbiJJWQ"
}
]
}
}
And I have a string with this text:
"Watch Take Off 2017 Malayalam Full Movie Online Free"
Now I need to get the linkextid of
"name": "Take Off 2017.MP4.mp4"
from JSON response. There is one more thing that I have so much similar data on the JSON response, but I need to the get name that matches maximum words from string using PHP.
<?php
$json_data='{"status":200,"msg":"OK","result":{"folders":[{"id":"3812454","name":".subtitles"},{"id":"3812455","name":".videothumb"}],"files":[{"name":"Angamaly Diaries HD.MP4.mp4","cblock":null,"sha1":"fcc2c99f2db6e3e8a700c3247206a1c2148e14cb","folderid":"3812453","upload_at":"1510255141","status":"active","size":"713544705","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"PjUv5IYA2J8"},{"name":"Take Off 2017.MP4.mp4","cblock":null,"sha1":"2fe7fb4d45322a085d41239d6429d1cc8e94e2ce","folderid":"3812453","upload_at":"1510255141","status":"active","size":"954148848","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"BIBcjWqF0_I"},{"name":"Rangoon 2017 Tamil.MP4.mp4","cblock":null,"sha1":"c685e7c11636982860ae7f34b671a20fc746feee","folderid":"3812453","upload_at":"1510255141","status":"active","size":"779899588","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"00D7GzP6mls"},{"name":"The Zookeeper’s Wife 2017.MP4.mp4.mp4","cblock":null,"sha1":"a143faafbd8a6eaf2276f25cd642ac3019d71ffc","folderid":"3812453","upload_at":"1510256266","status":"active","size":"550126461","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"bwUhqbiJJWQ"}]}}';
$data=json_decode($json_data,true);
$files=$data['result']['files'];
$search="Watch Take Off 2017 Malayalam Full Movie Online Free";
$search_array=explode(' ',$search);
foreach($search_array as $key=>$row){
$search_array[$key]=trim($row);
}
$match=[];
foreach($files as $key=>$row){
$match_count=0;
foreach($search_array as $s){
if(preg_match('/'.$s.'/',$row['name'])){
$match_count+=1;
}
}
$match[$key]=$match_count;
}
rsort($match);
print_r($files[$match[0]]['linkextid'])
?>
Not the best solution in the world but this should work:
<?php
function compare_strings($s1, $s2) {
$s1Words = explode(' ', $s1);
$s2Words = explode(' ', $s2);
$wordCount = 0;
foreach ($s1Words as $word) {
if ( strpos($s2Words, $word) ) {
$wordCount++;
}
}
return $wordCount;
}
function get_movie_linkextid($data, $name) {
$bestMatchIndex = 1;
$bestMatchScore = 0;
foreach ($data['result']['files'] as $i => $movie) {
$currentScore = compare_strings($movie['name'], $name);
if ($currentScore > $bestMatchScore) {
$bestMatchScore = $currentScore;
$bestMatchIndex = $i;
}
}
return $data['result']['files'][$bestMatchIndex]['linkextid'];
}
$data = json_decode($yourJsonData, true);
$name = "Watch Take Off 2017 Malayalam Full Movie Online Free";
echo get_movie_linkextid($data, $name);
?>
The code just parses your JSON into a variable and than goes through all the 'files' comparing their names with the string you provided the determine the best match. After that it just return the linkextid.
I Didn't tested this code but the important is to get the idea since you will have to adapt it to be more generic anyway.
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);
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'];
}
}
I have a list of movies and I want to compare to the Array of movies i got from Facebook Graph API.
Here is an example of what API is getting:
{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}...
The list I need to compare is pretty big, but here are some:
Wall Street, Shooter, Young Guns, Due Date...
Basically just compare 'Name' in 'data' with 'my list' of Movie titles. But can't figure out the syntax
Something like:
if ($movies->data->name == 'movie titles list') {echo "You like the same movies";}
I found this:
if (in_array('movie titles list', $a)) {echo "You like the same movies";}
Any thoughts would help me out.
Thanks
The data looks to be JSON encoded...
Try something like this: (json_decode)
$large_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}]}';
$json_to_array = json_decode($large_data, true);
var_dump(json_decode($large_data, true));
// You should now be able to compare the two array
echo print_r($json_to_array,true);
EDIT:
Improving on what #Eric posted
$large_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}]}';
$movie_list = json_decode($large_data, true);
$movieNames = array();
foreach($movie_list as $movies) {
foreach($movies as $movie) {
$movieNames[] = $movie['name'];
}
}
$myMovies = array('Wall Street', 'Shooter', 'Young Guns', 'Due Date');
$common_movies = array_intersect($movieNames, $myMovies);
foreach($common_movies as $common_movie) {
echo "We like the same movie ".$common_movie."<br />\n";
}
Another method:
<?php
$json_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}
]}';
$array_data = json_decode($json_data, TRUE);
$compare_list = array(
'Wall Street',
'Shooter',
'Young Guns',
'Due Date'
);
// <Marco Stumper> phpundhtml at web dot de
function in_array_multi($needle, $haystack) {
$found = false;
foreach ($haystack as $value) {
if ((is_array($value) && in_array_multi($needle, $value)) || $value == $needle) {
$found = true;
}
}
return $found;
}
foreach ($compare_list as $item) {
echo '<p>' . $item . (in_array_multi($item, $array_data) ? ' DOES ' : ' does NOT ') . 'exist within $array_data</p>' . PHP_EOL;
}
?>
Output:
<p>Wall Street does NOT exist within $array_data</p>
<p>Shooter DOES exist within $array_data</p>
<p>Young Guns does NOT exist within $array_data</p>
<p>Due Date does NOT exist within $array_data</p>
Use array_intersect(array1, array2, ... arrayN)
$large_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}
]}';
$movies = json_decode($large_data, true)['data'];
$movieNames = array();
//Get only the name from the movie list
foreach($movies as $movie) {
$movieNames[] = $movie['name'];
}
//Intersect with internal list
print_r(array_intersect($movieNames, $myMovies));