get value in multi dimensional array using php - 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);

Related

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>';
}

PHP Extracting a certain part of JSON string where username equals

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'];
}
}

php json_decode can't get to object

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;
}
}

formatted json format in php webservices

I am new in PHP. I am trying to format JSON. Here's the relevant code:
$query = mysql_query("SELECT *
FROM `micards` m
JOIN user u ON m.`mobile` = u.phone");
while ($row = mysql_fetch_assoc($query)) {
$response["success"] = 1;
$name = array('name'=>$row["name"],'email'=>$row["email"],'mobile'=>$row["mobile"]);
$phone[] = array('phone'=>$row["phone"],array('card'=>$name));
$response["contacts"] = $phone;
}
echo json_encode($response);
I'm getting this output:
{
"success": 1,
"contacts": [{
"phone": "919898989898",
"0": {
"card": {
"name": "abcd",
"email": "vwxy#test.com",
"mobile": "919898989898"
}
}
}, {
"phone": "919898989898",
"0": {
"card": {
"name": "abcd",
"email": "rstp#test.com",
"mobile": "919898989898"
}
}
}, {
"phone": "8686868686",
"0": {
"card": {
"name": "pan",
"email": "pnqr#gmail.com",
"mobile": "8686868686"
}
}
}, {
"phone": "8686868686",
"0": {
"card": {
"name": "monk",
"email": "abcd#gmail.com",
"mobile": "8686868686"
}
}
}]
}
But I want it to be:
{
"success": 1,
"contacts": [{
"phone": "919898989898",
{
"card": {
"name": "abcd",
"email": "vwxy#test.com",
"mobile": "919898989898"
}
},
{
"card": {
"name": "abcd",
"email": "rstp#test.com",
"mobile": "919898989898"
}
}
}],
[{
"phone": "8686868686",
{
"card": {
"name": "panky",
"email": "pnqr#gmail.com",
"mobile": "8686868686"
}
},
{
"card": {
"name": "panky",
"email": "abcd#gmail.com",
"mobile": "8686868686"
}
}
}]
}
What can I do to get the above output?
just change this part:
$phone[] = array('phone'=>$row["phone"],array('card'=>$name));
$response["contacts"] = $phone;
to
$response["contacts"][] = array('phone'=>$row["phone"],array('card'=>$name));
Just copy and paste this code
while ($row = mysql_fetch_assoc($query)) {
$response["success"] = 1;
$name = array('name'=>$row["name"],'email'=>$row["email"],'mobile'=>$row["mobile"]);
$response["contacts"][] = array('phone'=>$row["phone"],array('card'=>$name));
}
Please change
$phone[] = array('phone'=>$row["phone"],array('card'=>$name)) to
$phone[] = array('phone'=>$row["phone"],'card'=>$name)
;
My guess is that there is a problem with associative arrays and the way you are packing it. You can try to organize your response array like this:
$response = [
'success'=>1,
'contacts'=>[
'phone'=>$row['phone'],
'card'=>[
'name'=>$row['name'],
'email'=>$row['email'],
'mobile'=>$row['mobile']
]
]
];
It should work, didn't check it out thou.

How would you compare the names in a list to ones in an Array?

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));

Categories