I have an array and when I do
$array = json_decode($response, true);
print_r($array);
This is what I get from an array.
Array ( [data] => Array ( [0] => Array ( [id] => accenture [type] => companies [attributes] => Array ( [name] => Accenture [description] => Accenture is a global management consulting, technology services and outsourcing company, with more than 293,000 people serving clients in more than 120 countries. Combining unparalleled experience, comprehensive capabilities across all industries and business functions, and extensive research on the world’s most successful companies, Accenture collaborates with clients to help them become high-performance businesses and governments. The company generated net revenues of US$xxx for the fiscal year ended Aug. 31, 2013. Its home page is www.some-url.com. [employee_count_range] => 10001+ [founded_year] => 1989 [industries] => Array ( [0] => Information Technology & Services ) [website_url] => www.some-url.com [logo] => https://some-url/logo.png [square_logo] => https://some-url/square_logo.png [followed] => [claimed_status] => 1 [last_reviewed_at] => ) ) [1] => Array ( [id] => accenture-banglore [type] => companies [attributes] => Array ( [name] => Accenture, Banglore [description] => [employee_count_range] => [founded_year] => [industries] => [website_url] => [logo] => [square_logo] => [followed] => [claimed_status] => 1 [last_reviewed_at] => ) ) [2] => Array ( [id] => accenture-gmbh [type] => companies [attributes] => Array ( [name] => Accenture GmbH [description] => [employee_count_range] => [founded_year] => [industries] => [website_url] => [logo] => [square_logo] => [followed] => [claimed_status] => 1 [last_reviewed_at] => ) )
I tried with foreach loop to create a table and show the data in the table. This is how I try but I get an error "Invalid argument supplied for foreach()"
echo '<table>';
foreach($array as $result){
echo '<tr>';
echo '<td>'.$result->id.'</td>';
echo '<td>'.$result->name.'</td>';
echo '<td>'.$result->description.'</td>';
echo '<td>'.$result->funded_year.'</td>';
echo '</tr>';
}
echo '</table>';
Can anyone help me show the data in the table?
Your data for HTML table is inside data array key.
You should write:
foreach($array['data'] as $result){
or even better:
$array = json_decode($response, true);
$resultArray = isset($array['data']) ? $array['data'] : [];
echo '<table>';
foreach($resultArray as $result){
echo '<tr>';
echo '<td>'.(isset($result['id']) ? $result['id'] : '-') .'</td>';
echo '<td>'.(isset($result['attributes']['name']) ? $result['attributes']['name'] : '-').'</td>';
echo '<td>'.(isset($result['attributes']['description']) ? $result['attributes']['description'] : '-').'</td>';
echo '<td>'.(isset($result['attributes']['funded_year']) ? $result['attributes']['funded_year'] : '-').'</td>';
echo '</tr>';
}
echo '</table>';
http://php.net/manual/en/function.json-decode.php
Related
I'm to return data from a provider and the array supplied looks like this :
Array
(
[result] => Array
(
[0] => Array
(
[problem_id.u_root_cause] =>
[number] => INC0000001
[short_description] => Unable to print
[u_alert_check] =>
[u_business_service] => Array
(
[display_value] => Printer
[link] => https://redacted/37bc8af837c3820ca7e3b15ec3990e1c
)
[assignment_group] => Array
(
[display_value] => Printer Support
[link] => https://redacted/b699595c37dac200a7e3b15ec3990eb1
)
[u_service_impact_duration] => 57 Minutes
[u_summary_notes] => Changed USB cable
[u_environment] => Production (PD)
[problem_id] =>
[priority] => 3 - P3
[u_business_services_impacted] =>
)
Now, I'm able to return most of the data like this,
foreach($data['result'] as $line){
echo $line['number'];
echo '<br>';
echo $line['short_description'];
}
The above returns the number and short_description from the array.
The trouble I have is how do I return u_business_service in the same line?
For acessing the multidimensional array you may use:
echo $line['u_business_service']['display_value'];
echo $line['u_business_service']['link'];
I have the following problem.
I am trying to read a Json file but I am not getting the desired result. I have the following data.
I would like to read the features and there is a mistake in finding out somewhere.
I get the error message when reading out:
Warning: Illegal string offset 'features'
Output
Array
(
[objectIdFieldName] => OBJECTID
[uniqueIdField] => Array
(
[name] => OBJECTID
[isSystemMaintained] => 1
)
[globalIdFieldName] =>
[geometryProperties] => Array
(
[shapeAreaFieldName] => Shape__Area
[shapeLengthFieldName] => Shape__Length
[units] => esriMeters
)
[geometryType] => esriGeometryPolygon
[spatialReference] => Array
(
[wkid] => 4326
[latestWkid] => 4326
)
[fields] => Array
(
[0] => Array
(
[name] => GEN
[type] => esriFieldTypeString
[alias] => GEN
[sqlType] => sqlTypeOther
[length] => 33
[domain] =>
[defaultValue] =>
)
[1] => Array
(
[name] => cases
[type] => esriFieldTypeInteger
[alias] => Anzahl Fälle
[sqlType] => sqlTypeOther
[domain] =>
[defaultValue] =>
)
[2] => Array
(
[name] => deaths
[type] => esriFieldTypeInteger
[alias] => Anzahl Todesfälle
[sqlType] => sqlTypeOther
[domain] =>
[defaultValue] =>
)
)
[features] => Array
(
[0] => Array
(
[attributes] => Array
(
[GEN] => Celle
[cases] => 220
[deaths] => 15
)
...........
My Code
$url = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=GEN%20%3D%20%27CELLE%27&outFields=GEN,cases,deaths&outSR=4326&f=json";
$json = file_get_contents($url);
$data = json_decode($json,true); //decode json result as array and thenloop it
print '<pre>';
print_r($data);
foreach($data as $row){
echo $row['features']->$row['attributes']->$row['GEN'];
}
Where am I wrong in reading?
It only has to be read what is in parentheses right?
So actually features-> attributes-> Gen to get the GEN query
Let's try change to this.
foreach($data as $row){
echo $row['features'][0]['attributes']['GEN'];
}
Sorry this is my fault when seem does'nt read clearly your question.
With GEN attribute you don't use loop to get this value.
If you wanna get GEN only your code should be that.
$url = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=GEN%20%3D%20%27CELLE%27&outFields=GEN,cases,deaths&outSR=4326&f=json";
$json = file_get_contents($url);
$data = (array) json_decode($json, true); //decode json result as array and thenloop it
print '<pre>';
print_r($data);
echo $data['features']['attributes']['GEN'];
// foreach($data as $row){
// echo $row['features']->$row['attributes']->$row['GEN'];
// }
I have an xml response for a DHL tracking and i want to echo specific elements on my php page.
I use the following code to print out the tracking results without formatting:
print_r($response);
The xml response looks like this:
Array
(
[TrackingResponse] => Array
(
[xmlns:req] => http://www.dhl.com
[xmlns:xsi] => http://www.w3.org/2001/XMLSchema-instance
[xsi:schemaLocation] => http://www.dhl.com TrackingResponse.xsd
[Response] => Array
(
[ServiceHeader] => Array
(
[MessageTime] => 2013-12-12T11:51:05+00:00
[MessageReference] => j2xfhcBpCE2yd9gbeC5tjqxIX8xjDpZ1
[SiteID] => iraqnova
)
)
[AWBInfo] => Array
(
[AWBNumber] => 8564385550
[Status] => Array
(
[ActionStatus] => success
)
[ShipmentInfo] => Array
(
[OriginServiceArea] => Array
(
[ServiceAreaCode] => FRA
[Description] => FRANKFURT - GERMANY
)
[DestinationServiceArea] => Array
(
[ServiceAreaCode] => MLA
[Description] => MALTA - MALTA
)
[ShipperName] => STANDARD CHARTERED BANK
[ShipperAccountNumber] => 144193851
[ConsigneeName] => BANK OF VALLETTA P.L.C
[ShipmentDate] => 2013-02-14T15:14:00
[Pieces] => 1
[Weight] => 0.08
[WeightUnit] => K
[GlobalProductCode] => U
[ShipmentDesc] => 1402130018
[DlvyNotificationFlag] => Y
[Shipper] => Array
(
[City] => Frankfurt/Main
[PostalCode] => 60486
[CountryCode] => DE
)
[Consignee] => Array
(
[City] => Santa Venera
[PostalCode] => 9030
[CountryCode] => MT
)
[ShipperReference] => Array
(
[ReferenceID] => Doc
)
)
)
)
)
I'm getting lost with so many foreach loops to get to the specific xml tags inside the [ShipmentInfo] tag:
foreach($response as $tag){
echo $tag['ShipmentInfo'];
}
The sample tracking number and info, from the DHL XML Service Validation website http://xmlpitest-ea.dhl.com/serviceval/jsps/main/Main_menu.jsp
Thank you,
$arr['TrackingResponse']['AWBInfo']['ShipmentInfo'] will lead to the shipment info and then iterate over this using foreach.
Like -
if(is_array($arr['TrackingResponse']['AWBInfo']['ShipmentInfo'])) {
foreach(is_array($arr['TrackingResponse']['AWBInfo']['ShipmentInfo']) as $shiptagkey=>$shiptagval)
{
echo $shiptagkey, " ", $shiptagval;
}
}
Although $shiptagval itself going to be an array so you need to care about this as well.
print_r($response ['TrackingResponse']['AWBInfo']['ShipmentInfo']);
or if you don't know the path: (pseudocode)
function findAndEcho($obj,$tag) {
for $obj as $key => $val {
if $key = $tag {
print_r($val)
}
else if is_array($val) {
findAndEcho($val,$tag)
}
}
}
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'];
}
I am attempting to use a foreach to output the array below. I have created this array via array_push() based on preg_match if/else.
Array (
[0] => Array (
[date] =>
[clickurl] => some data
[url] => some data
[dispurl] => some Data...
[title] => Transformers: Revenge of the Fallen : Reviews
[abstract] => "Transformers: Revenge of the Fallen" is a horrible experience of unbearable length, briefly punctuated by three or four amusing moments.
)
[1] => Array (
[date] =>
[clickurl] => some data
[url] => some data
[dispurl] => some Data...
[title] => Transformers : Reviews
[abstract] => After a string of bad-to-mediocre films, director Michael Bay scores with blockbuster battling robots in "Transformers."
)
)
When attempting to output the array:
foreach ($reviewArr as $review) {
echo($review['clickurl']. '<br/><br/>');
}
The output is "A" which is the first letter of Array at the start of the array above. This is the same result as using $review[0];
When using:
foreach ($reviewArr as $review) {
echo($review. '<br/><br/>');
}
the output is:
Array (
[date] =>
[clickurl] => some data
[url] => some data
[dispurl] => some data...
[title] => Transformers : Reviews
[abstract] => After a string of bad-to-mediocre films, director Michael Bay scores with blockbuster battling robots in "Transformers."
)
I am not sure why this is happening. Any help will be greatly appreciated.
thanks!
UPDATE =
This is the original Array that I parse below to split into two different arrays.
Array
(
[bossresponse] => Array
(
[responsecode] => 200
[web] => Array
(
[start] => 0
[count] => 14
[totalresults] => 14
[results] => Array
(
[0] => Array
(
[date] =>
[clickurl] => http://url.com/1
[url] => http://url.com/1
[dispurl] => http://url.com/1...
[title] => Title of Content 1
[abstract] => This is the summary, This is the summary, This is the summary, ...
)
[1] => Array
(
[date] =>
[clickurl] => http://url.com/2
[url] => http://url.com/2
[dispurl] => http://url.com/2...
[title] => Title of Content 2
[abstract] => This is the summary, This is the summary, This is the summary, ...
)
)
)
)
)
This is how I am setting the $reviewArr[].
foreach ($results['bossresponse']['web']['results'] as $key => $result) {
$url = $result['clickurl'];
$title = $result['title'];
$abstract = $result['abstract'];
$resultItem = print_r($results['bossresponse']['web']['results'][$key], true);
if (preg_match ("/reviews/i", "$url")) {
array_push($reviewArr, "$resultItem");
} else {
array_push($resultsArr, "$resultItem");
}
}
UPDATE #2 -
I see thanks to #fabio that I am simply setting a string with $resultItem above. How can I achieve creating a multidimensional array? How can I build this as an array - all of my attempts returned errors, or a string.
Array
(
[0] => Array
(
[date] =>
[clickurl] => http://url.com/1
[url] => http://url.com/1
[dispurl] => http://url.com/1...
[title] => Title of Content 1
[abstract] => This is the summary, This is the summary, This is the summary, ...
)
[1] => Array
(
[date] =>
[clickurl] => http://url.com/2
[url] => http://url.com/2
[dispurl] => http://url.com/2...
[title] => Title of Content 2
[abstract] => This is the summary, This is the summary, This is the summary, ...
)
)
Change:
foreach ($results['bossresponse']['web']['results'] as $key => $result) {
$url = $result['clickurl'];
$title = $result['title'];
$abstract = $result['abstract'];
$resultItem = print_r($results['bossresponse']['web']['results'][$key], true);
if (preg_match ("/reviews/i", "$url")) {
array_push($reviewArr, "$resultItem");
} else {
array_push($resultsArr, "$resultItem");
}
}
to:
foreach ($results['bossresponse']['web']['results'] as $key => $result) {
if (preg_match ("/reviews/i", $result['clickurl'])) {
$reviewArr[] = $result;
} else {
$resultsArr[] = $result;
}
}
I don't know how you are pushing items on your array, but I think this could do the trick:
foreach ($reviewArr as $index=>$review) {
echo($review['clickurl']. '<br/><br/>');
}
For what weird reason are you filling the array with the return value of print_r???
// this will return a string
$resultItem = print_r($results['bossresponse']['web']['results'][$key], true);
So here is the reason of your behaviour: you're printing the first character of the print_r return value which is the string representation of $results[...][...] array.
Try it by yourself
$foo = "Hello world";
echo $foo[0]; // output H
P.S. echo($review. '<br/><br/>'); will output the whole string which is the print_r output.