I'm getting a warning on a json decode foreach within a foreach (although the code works which is strange) the warning is: Warning: Invalid argument supplied for foreach() it is referring to this line: foreach ($value as $val) {
Here is the JSON response:
Array
(
[ACTION] => avail.datacenters
[DATA] => Array
(
[0] => Array
(
[LOCATION] => Dallas, TX, USA
[DATACENTERID] => 2
[ABBR] => dallas
)
[1] => Array
(
[LOCATION] => Fremont, CA, USA
[DATACENTERID] => 3
[ABBR] => fremont
)
[2] => Array
(
[LOCATION] => Atlanta, GA, USA
[DATACENTERID] => 4
[ABBR] => atlanta
)
[3] => Array
(
[LOCATION] => Newark, NJ, USA
[DATACENTERID] => 6
[ABBR] => newark
)
[4] => Array
(
[LOCATION] => London, England, UK
[DATACENTERID] => 7
[ABBR] => london
)
[5] => Array
(
[LOCATION] => Tokyo, JP
[DATACENTERID] => 8
[ABBR] => tokyo
)
[6] => Array
(
[LOCATION] => Singapore, SG
[DATACENTERID] => 9
[ABBR] => singapore
)
[7] => Array
(
[LOCATION] => Frankfurt, DE
[DATACENTERID] => 10
[ABBR] => frankfurt
)
[8] => Array
(
[LOCATION] => Tokyo 2, JP
[DATACENTERID] => 11
[ABBR] => shinagawa1
)
)
[ERRORARRAY] => Array
(
)
)
My foreach code:
$randDCID = array();
foreach ($linodeRegions as $value) {
foreach ($value as $val) {
echo $val['DATACENTERID'] . "<br />";
$randDCID[] = $val['DATACENTERID'];
}
}
Can anyone see the issue on the warning (although it is outputting the desired results).
The error is probably coming from the ACTION index and the corresponding value(which is string) of the array. Assuming the fact that $linodeRegions in your original array, there's no need to create nested loops in this case, simply use a foreach loop like this:
$randDCID = array();
foreach ($linodeRegions['DATA'] as $value) {
echo $value['DATACENTERID'] . "<br />";
$randDCID[] = $value['DATACENTERID'];
}
Related
I'm trying to find out in a simple way to display a clean like this format
Having a hard time to spread the data in this associative array got this from an API
Array (
[wind] => Array (
[speed] => 5
[direction] => North West
[directionDegrees] => 310
[unit] => KT
)
[visibility] => Array (
[mainVisibility] => 10SM
)
[clouds] => Array (
[0] => Array (
[height] => 25000
[quantity] => few
)
)
[cavok] =>
[remark] => automated station with a precipitation discriminator sea level pressure of 1021.7 HPa hourly temperature of 17.2°C and dew point of -1.1°C
[day] => 6
[time] => 22:52:00
[airport] => Array (
[name] => Hartsfield Jackson Atlanta International Airport
[city] => Atlanta
[country] => Array (
[name] => United States
)
[iata] => ATL
[icao] => KATL
[latitude] => 33.6367
[longitude] => -84.428101
[altitude] => 1026
[timezone] => -5
[dst] => A
)
[message] => KATL 062252Z 31005KT 10SM FEW250 17/M01 A3017 RMK AO2 SLP217 T01721011
[station] => KATL
[temperature] => 17
[dewPoint] => -1
[altimeter] => 1021
[nosig] =>
[auto] =>
[amendment] =>
[nil] =>
[corrected] =>
[cancelled] =>
)
I'm not good at programming as this is our assignment from our school I'm looking at to loop the array but I can't seem to find a way how to do it.
You can use this parser source code and make your own solution on the base
https://github.com/SafranCassiopee/php-metar-decoder
or simple way to get field
$arr = '$yourDataArrayHere$';
$metarRw = $arr['message']
echo 'Metar message '.$metarRw;
$airportName = $arr['airport']['name']
echo 'Airport name '.$airportName;
etc.
I can't for the life me return single values of my multidimensional array from database. For example, I want to return the value of each key to return in table columns.
This is the array coming from the database:
Array
(
[0] => stdClass Object
(
[student_id] => lvzr0001
[fname] => Hamza
[lname] => ibrahimi
[student_email] => Hamza_ib2#hotmail.com
[course] => CPAN 220 D30
[full_name] => asdfddd
[institution] => asdf
[position] => sadf
[proc_email] => Hamza_ib2#hotmail.com
[phone] => 14168334599
[address] => 20 edgecliffe golfway
[city] => Toronto
[prov_state] => Ont
[postal_code] => M3C 3A4
[country] => Canada
[comments] => adfadsfasdfasdfas
)
[1] => stdClass Object
(
[student_id] => 56gfdsgdfs
[fname] => zxcv
[lname] => cvcvz
[student_email] => dsfb2#hotmail.com
[course] => ELIC 101 90
[full_name] => dfa
[institution] => asdf
[position] => zxcvzxcv
[proc_email] => zxcvzxvc#hotmail.com
[phone] => 4002452345
[address] => 102 yorkland st
[city] => Richmond Hill
[prov_state] => Ont
[postal_code] => l4s1a1
[country] => Canada
[comments] => xzcvzxcv
)
)
I want to get a specific column result like this:
<?php
global $wpdb;
$displayQuery = $wpdb->get_results("SELECT * FROM viewoffcampusproctorrequests");
echo '<pre>';
print_r ($displayQuery);
echo '</pre>';
foreach($displayQuery as $key => $value){
foreach($value as $title => $description){
echo $description['fname'];
}
}
But I only get the entire key values when I echo $description;. How would I access each key item in my array?
You're close: $value is an object, so you can retrieve a particular key/value pair. If you want the value for fname for each object:
foreach($displayQuery as $key => $value){
echo $value->fname;
}
Hi i have an array like below. I want to search partial data from this array.
for example: i want to search "New Delhi" then i got array where city = Delhi, and search "Raigad" then got array where city = Raigarh
Array(
[56] => Array
(
[city] => Davangere
[product_id] => 14
[tier] => Tier 4
)
[57] => Array
(
[city] => Dehradun
[product_id] => 14
[tier] => Tier 3
)
[58] => Array
(
[city] => Delhi
[product_id] => 14
[tier] => Metro
)
[59] => Array
(
[city] => Delhi
[product_id] => 14
[tier] => Metro
)
[60] => Array
(
[city] => Raigarh
[product_id] => 14
[tier] => Metro
)
)
Make use of similar_text to attain this -
$finalArray = array();
$searchString = "New Delhi";
//Loop through your array
foreach ($your_array as $key => $value) {
similar_text($searchString, $value['city'], $percentageSimilarity);
//if percentage similarity between the text is above 70%, add to to our final array
if ($percentageSimilarity > 70) {
$finalArray[$key] = $value;
}
}
var_dump($finalArray);
Works for Delhi and Raigarh.
I have json return string like given below. I want to extract cancellation Policy list of objects like cutoff Time and refund In Percentage. I tried using for-loop but it didn't help me. Can you please help me on extracting this.
Array (
[apiStatus] => Array ( [success] => 1 [message] => SUCCESS ) <br>
[apiAvailableBuses] => Array ( <br>
[0] => Array ( [droppingPoints] => [availableSeats] => 41 <br>[partialCancellationAllowed] => [arrivalTime] => 08:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:00PM [location] => Ameerpet,|Jeans Corner 9687452130 [id] => 6 ) [1] => Array ( [time] => 09:15PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 09:10PM [location] => Kondapur,Toyota Show room [id] => 2244 ) ) [operatorName] => Deepak Travels [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6622 [fare] => 800 [busType] => 2+1 Hi-Tech Non A/c [routeScheduleId] => 6622 [commPCT] => 0 [operatorId] => 213 [inventoryType] => 0 ) <br>
[1] => Array ( [droppingPoints] => [availableSeats] => 41 [partialCancellationAllowed] => [arrivalTime] => 07:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:10PM [location] => Ameerpet,|Jeans Corner [id] => 6 ) [1] => Array ( [time] => 09:00PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 08:30PM [location] => KUKATPALLY,JNTU [id] => 2230 ) ) [operatorName] => Dhanunjayabus [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6743 [fare] => 900 [busType] => VOLVO [routeScheduleId] => 6743 [commPCT] => 0 [operatorId] => 233 [inventoryType] => 0 )
)
)
Use a foreach() for it like so:
foreach ($your_response['apiAvailableBuses'] as $el) {
$cancellationPolicy[] = $el['cancellationPolicy'];
}
Try this:
foreach($data['apiStatus']['apiAvailableBuses'] as $item) {
foreach($item['cancellationPolicy'] as $key => $json) {
$jsonDecoded = json_decode($json, true);
// And you will have access to the data like this
// $jsonDecoded['cutoffTime'];
// $jsonDecoded['refundInPercentage'];
}
}
$response = json_decode($apiResponse);
$cancellationPolicies = [];
foreach ($response->apiAvailableBuses as $availableBus) {
$cancellationPolicies[] = $availableBus['cancellationPolicy'];
// if you want to display something you can simply do it like this;
echo $availableBus['cancellationPolicy']->cutoffTime;
}
How would i get the value of a key in an array?
The array is done by google shopping api which is:
// Valid source values are "public", "cx:cse", and "gan:pid"
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#products-feed
$source = "public";
// For more information about full text search with the shopping API, please
// see http://code.google.com/apis/shopping/search/v1/getting_started.html#text-search
$query = "\"mp3 player\" | ipod";
//The order in which the API returns products is defined by a ranking criterion.
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#ranking
$ranking = "relevancy";
$results = $service->products->listProducts($source, array(
"country" => "UK",
"q" => $query,
"rankBy" => $ranking,
));
print "<h1>Shopping Results</h1><pre>" . print_r($results, true) . "</pre>";
I have the following array which outputs:
Shopping Results
Array
(
[kind] => shopping#products
[etag] => "*********"
[id] => tag:google.com,2010:shopping/products
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy
[nextLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy&startIndex=26
[totalItems] => 771622
[startIndex] => 1
[itemsPerPage] => 25
[currentItemCount] => 25
[requestId] => 0CMjH976CqbECFYNWtAodLRwAAA
[items] => Array
(
[0] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/11254757413841304510
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/11254757413841304510
[product] => Array
(
[googleId] => 11254757413841304510
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[description] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[link] => http://www.amazon.co.uk/dp/B0040GIZTI/ref=asc_df_B0040GIZTI8843997?smid=A1YZ4RXO7GUOYN&tag=googlecouk06-21&linkCode=asn&creative=22218&creativeASIN=B0040GIZTI
[brand] => Apple
[condition] => new
[gtin] => 00885909394739
[gtins] => Array
(
[0] => 00885909394739
)
[mpns] => Array
(
[0] => MC540BT/A
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 135.95
[shipping] => 1.99
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/41p2rNmazRL.jpg
[status] => available
)
)
)
)
[1] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/4597224105326146239
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/4597224105326146239
[product] => Array
(
[googleId] => 4597224105326146239
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => SanDisk Sansa Clip+ 8GB MP3 Player with Radio and Expandable MicroSD/SDHC Slot - Black
[description] => 8 GB memory Digital FM-tuner with 40 preset radio stations Extendable microSD/microSDHC card slot
[link] => http://www.amazon.co.uk/dp/B002NX0ME6/ref=asc_df_B002NX0ME68843997?smid=A3P5ROKL5A1OLE&tag=googlecouk06-21&linkCode=asn&creative=22206&creativeASIN=B002NX0ME6
[brand] => SanDisk
[condition] => new
[gtin] => 00619659059989
[gtins] => Array
(
[0] => 00619659059989
)
[mpns] => Array
(
[0] => SDMX18-008G-E46K
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 46.95
[shipping] => 0
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/419U6bYDF1L.jpg
[status] => available
)
)
)
)
I don't need all this data i just need 3-4 of the keys but how would i access them? How would i echo the value of say [title] from each array?
This should work:
foreach( $results as $result)
foreach( $result['product'] as $product)
echo $product['title'];
You could either loop through the array like pointed out above or possibly use array_walk_recursive like this:
$title_array = array();
array_walk_recursive($input_array, 'find_titles');
function find_titles($value, $key) {
global $title_array;
if ($key == 'title') {
$title_array[] = $value;
}
}
This might be a better solution if you you are not certain what the structure of the input array will be (i.e. how many levels deep the key you are looking for is nested).
To output the title of each product in $results:
foreach ($results as $result) {
echo $result['product']['title'];
}
Consider using array_walk_recursive
Working example
<?php
$a = array("hai", array("ha"=>1, "hai"=>2, array("a"=>1, "b"=>2)));
function test($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($a, 'test');
0 holds hai
ha holds 1
hai holds 2
a holds 1
b holds 2
If you are interested only in title
Consider using foreach
foreach($results['item'] as $result) {
echo $result['product']['title'];
}