PHP:problems in getting values from a associative array using foreach - php

I am trying to get values from a complex associative array it is obtained from an xml file.Here is the actual output of array (https://www.dropbox.com/s/k6lxrx6h9x3x83u/xml-first.txt?dl=0).
Here is a sample
Array
(
[drawserialnumber] => 48285
[lotteryname] => Akshaya
[shortname] => AK
[drawdate] => 2015-06-17
[drawheld] => Array
(
)
[drawnumber] => 194
[drawvenew] => SREE CHITHRA HOME AUDITORIUM, PAZHAVANGADI, EAST FORT, THIRUVANANTHAPURAM
[approvedby] => A.Jayakumar
[approverdesig] => Deputy Director
[approveroffice] => Directorate Of State Lotteries , Vikas Bhavan,tvm
[prizes] => Array
(
[prizedetails] => Array
(
[0] => Array
(
[prizeno] => 1
[prizedesc] => Rs :6,500,000/-
[totalamt] => 6500000
[conslation] => f
[prizeticket] => Array
(
[seriesname] => AK
[digit] => 279045
[district] => THRISSUR
)
)
[1] => Array
(
[prizeno] => 1
[prizedesc] => Rs :10,000/-
[totalamt] => 10000
[conslation] => t
[prizeticket] => Array
(
[0] => Array
(
[seriesname] => AJ
[digit] => 279045
[district] => NIL
)
[1] => Array
(
[seriesname] => AR
[digit] => 279045
[district] => NIL
)
[2] => Array
(
[seriesname] => AM
[digit] => 279045
[district] => NIL
)
[3] => Array
(
[seriesname] => AO
[digit] => 279045
[district] => NIL
)
[4] => Array
(
[seriesname] => AP
[digit] => 279045
[district] => NIL
)
[5] => Array
(
[seriesname] => AL
[digit] => 279045
[district] => NIL
)
)
)
[2] => Array
(
[prizeno] => 2
[prizedesc] => Rs :200,000/-
[totalamt] => 200000
[conslation] => f
[prizeticket] => Array
(
[0] => Array
(
[seriesname] => AR
[digit] => 420734
[district] => KANNUR
)
[1] => Array
(
[seriesname] => AJ
[digit] => 221136
[district] => ALAPPUZHA
)
[2] => Array
(
[seriesname] => AK
[digit] => 825429
[district] => WAYANAD
)
[3] => Array
(
[seriesname] => AL
[digit] => 171621
[district] => THIRUVANANTHAPURAM
)
[4] => Array
(
[seriesname] => AM
[digit] => 786170
[district] => ERNAKULAM
)
[5] => Array
(
[seriesname] => AO
[digit] => 668158
[district] => PALAKKAD
)
[6] => Array
(
[seriesname] => AP
[digit] => 244326
[district] => KANNUR
)
)
)
[3] => Array
(
[prizeno] => 3
[prizedesc] => Rs :10,000/-
[totalamt] => 10000
[conslation] => f
[prizeticket] => Array
(
[seriesname] => Array
(
)
[digit] => 25426
[district] => Array
(
)
)
)
[4] => Array
(
[prizeno] => 4
[prizedesc] => Rs :5,000/-
[totalamt] => 5000
[conslation] => f
[prizeticket] => Array
(
[0] => Array
(
[seriesname] => Array
(
)
[digit] => 6989
[district] => Array
(
)
)
[1] => Array
(
[seriesname] => Array
(
)
[digit] => 3242
[district] => Array
(
)
)
and so on for may occurances
Now i want to get the details to an html table ,its almost done but the problem is
pricedetails array.
Here is the code for getting pricedetails
foreach ($data['prizes'] as $prizes) {
foreach($prizes as $prize){
echo '<pre>';
print_r($prize);
echo '</pre>';
$temp=$prize['prizeticket'];
foreach($temp as $ticket){
print_r($ticket);
}
}
}
Here is the two iterations of Print_r($prize)
Array
(
[prizeno] => 1
[prizedesc] => Rs :6,500,000/-
[totalamt] => 6500000
[conslation] => f
[prizeticket] => Array
(
[seriesname] => AK
[digit] => 279045
[district] => THRISSUR
)
)
Array
(
[prizeno] => 1
[prizedesc] => Rs :10,000/-
[totalamt] => 10000
[conslation] => t
[prizeticket] => Array
(
[0] => Array
(
[seriesname] => AJ
[digit] => 279045
[district] => NIL
)
[1] => Array
(
[seriesname] => AR
[digit] => 279045
[district] => NIL
)
[2] => Array
(
[seriesname] => AM
[digit] => 279045
[district] => NIL
)
[3] => Array
(
[seriesname] => AO
[digit] => 279045
[district] => NIL
)
[4] => Array
(
[seriesname] => AP
[digit] => 279045
[district] => NIL
)
[5] => Array
(
[seriesname] => AL
[digit] => 279045
[district] => NIL
)
)
)
As you see the first iteration contains only one sub array under prizedetails and the second iterations contains more than one sub arrays under prizedetails.
The problem i can't get the values with both key-value pairs.
print_r($ticket) output
AK
279045
THRISSUR
Array
(
[seriesname] => AJ
[digit] => 279045
[district] => NIL
)
Array
(
[seriesname] => AR
[digit] => 279045
[district] => NIL
)
Notice that first output AK
279045
THRISSUR
printed without any key and its like a text and the rest is outputted correctly,but i need to print all of with the array keys.I know this is because the print_r($prize) first iteration contains only one sub array under prizedetails.How can i solve it?
UPDATE
Code for parsing xml
$data=json_decode(json_encode((array)simplexml_load_string($lottery)),1);

Your code is behaving correctly. You need to alter the code such that "IF" prizeticket has one item, it does one thing, "ELSE" it does something else.
if(!isset($prize['prizeticket'][0])) // It has one item
print_r($prize['prizeticket']);
else foreach($prize['prizeticket'] as $ticket)
print_r($ticket);
This is a good place to use a function. Suppose it was named `handle_a_ticket($ticket)', you would replace print_r with handle_a_ticket.

My first reaction is that the XML has a typo.
[prizeticket] => Array
(
[seriesname] => AK
[digit] => 279045
[district] => THRISSUR
)
Should instead look like:
[prizeticket] => Array
(
[0] => Array
(
[seriesname] => AK
[digit] => 279045
[district] => THRISSUR
)
If you have some requirement that you absolutely must leave the XML the way it is, I'd suggest checking for the existence of index 0 like this:
foreach($temp as $tickets) {
if(!isset($tickets[0]) {
//do something with $ticket
}
else {
foreach($tickets as $ticket) {
//do something with $ticket
}
}

Finally i found the solution based on #RiggsFolly's comments.
$xml=simplexml_load_file('AK-194.xml');
foreach($xml->prizes as $prize){
foreach($prize->prizedetails as $details){
foreach($details->prizeticket as $tickets){
print_r($tickets);
}
}
}

Related

Laravel - How can I add new array key with value to the collection output

I have this query:
$get_products = Cache::rememberForever('all_imports', function () use ($collection) {
return DB::connection('mongodb')->collection( $collection )->paginate( self::NO_OF_PRODUCTS );
});
If I print_r this output:
echo '<pre>';
print_r( $get_products );
echo '</pre>';
I got this request:
Illuminate\Pagination\LengthAwarePaginator Object
(
[items:protected] => Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => Array
(
[_id] => MongoDB\BSON\ObjectId Object
(
[oid] => 639e0f59889929ce620f4e9c
)
[id] => 35035
[availability] => In stock
[brand] => Bogas Primavara Vara
[condition] => new
[date_add] => 1671303001
[date_upd] => 1673865782
[description] => Rochie dama scurta catifea neagra Antonietta Bogas Rochie dama scurta catifea neagra Antonietta Bogas
[image_link] => https://www.bogas.ro/continut/produse/35035/1000/rochie-dama-scurta-catifea-neagra-antonietta-bogas_126777.jpeg
[link] => https://www.bogas.ro/rochie-dama-scurta-catifea-neagra-antonietta-bogas/?utm_source=googlemerchantcenter&utm_medium=cpc&utm_campaign=direct_link
[price] => 229.99 RON
[product_type] => Rochii
[sale_price] => 149.99 RON
[title] => Rochie dama scurta catifea neagra Antonietta Bogas
[update_history] => Array
(
[0] => Array
(
[id_feed] => 269
[feed_name] => bogas direct
[date_upd] => 1673865782
[field_history] => Array
(
)
)
)
[all_sizes] => Array
(
[0] => XS
[1] => S
[2] => M
[3] => L
[4] => XL
)
[sizes_out_of_stock] => Array
(
)
[additional_image_link] => Array
(
[0] => https://www.bogas.ro/continut/produse/35035/520/rochie-dama-scurta-catifea-neagra-antonietta-bogas_126775.jpeg
[1] => https://www.bogas.ro/continut/produse/35035/520/rochie-dama-scurta-catifea-neagra-antonietta-bogas_126776.jpeg
)
[all_attributes] => Array
(
[0] => Negru
[1] => Negru
[2] => Negru
[3] => Negru
[4] => Negru
)
[ean13] =>
[in_stock_attributes] => Array
(
[0] => Negru
[1] => Negru
[2] => Negru
[3] => Negru
[4] => Negru
)
[specs] => Array
(
[Material] => Catifea
)
[total_optiuni_out_of_stock] => Array
(
)
[clicks_last_30days_present] => 0
[field_update] => Array
(
[clicks_last_30days_present] => 1673872147
[cost_last_30days_present] => 1673872147
[conversions_last_30days_present] => 1673872147
[conversions_value_last_30days_present] => 1673872147
[impressions_last_30days_present] => 1673872147
[roas_last_30days_present] => 1673872147
)
[cost_last_30days_present] => 0
[conversions_last_30days_present] => 0
[conversions_value_last_30days_present] => 0
[impressions_last_30days_present] => 4
[roas_last_30days_present] => 0
)
)
[escapeWhenCastingToString:protected] =>
)
[perPage:protected] => 1
[currentPage:protected] => 1
[path:protected] => http://127.0.0.1:8000/api/price-monitor/matching/your-product/97-0048-2571-870/1
[query:protected] => Array
(
)
[fragment:protected] =>
[pageName:protected] => page
[onEachSide] => 3
[options:protected] => Array
(
[path] => http://127.0.0.1:8000/api/price-monitor/matching/your-product/97-0048-2571-870/1
[pageName] => page
)
[total:protected] => 830
[lastPage:protected] => 830
)
Now, I want to added a new array key with value to the output. So, I am doing this:
if( isset( $get_products[0]['additional_image_link'] ) && ! empty( $get_products[0]['additional_image_link'] ) ) {
$get_products[0]['carousel_images'] = $get_products[0]['additional_image_link'];
}
But I got an error message :
Indirect modification of overloaded element of
Illuminate\Pagination\LengthAwarePaginator has no effect

How to process complex json object in PHP

I have a working PHP app running in Bluemix that I want to extend to call a RESTful service (Insights for Twitter). I've been able to call the service, retrieve the json body, and use json_decode as follows to create an array:
$insightList = json_decode($guzzleResponse ->getBody(), true);
However, I can't figure out how to get access to the field I'm interested in. I've searched for solution on the web and tried a few approaches that looked promising, but when I tried to integrate them, I couldn't get them to work. I'm a bit of a PHP novice, so if something doesn't work I'm not sure how to proceed.
The json structure is quite complex, with three top-level arrays - search, tweets, and next. I'm interested in the second of these, tweets. It's a pretty complex array - there is one entry per tweet. The field I want right now is tweets.cde.message.body. You can find the full schema here: https://cdeservice.eu-gb.mybluemix.net/rest-api/#!/messages/getTweets
This is the code I have so far:
foreach($insightList as $cde) {
foreach($cde as $message) {
$insight = $message['body'];
if(strlen($insight) > 60) {
$posts[] = array(
'id' => 99999999,
//Temp; remove links from the text
'text' => $insight,
'category' => $insightCategory,
'image' => 'false'
);
}
}
}
Here's a print_r of $insightList:
[search] => Array (
[results] => 28
[current] => 28
)
[tweets] => Array (
[0] => Array (
[cde] => Array (
[author] => Array (
[gender] => male
[parenthood] => Array (
[isParent] => unknown
)
[location] => Array (
[country] =>
)
[maritalStatus] => Array (
[isMarried] => unknown
)
)
[content] => Array (
[sentiment] => Array (
[evidence] => Array ( )
[polarity] => NEUTRAL
)
)
)
[message] => Array (
[postedTime] => 2015-01-13T09:42:16.000Z
[verb] => share
[link] => http://twitter.com/zWDOM/statuses/554936456477933569
[generator] => Array (
[displayName] => Twitter Web Client
[link] => http://twitter.com
)
[body] => RT #VisualSuccess: "Mainframe & Cloud" Magazine wurde soeben publiziert! http://www.twitter.com #zWDOM #Rocket #JohnKnutson_IBM
[favoritesCount] => 0
[objectType] => activity
[actor] => Array (
[summary] => Seit über 25 Jahren im Mainframebereich, derzeit als Senior Consultant und IT Architekt für zEnterprise und Projektmanager beim IBM BP Cancom in Köln
[image] => https://pbs.twimg.com/profile_images/424202233463308288/XQquUcnh_normal.jpeg
[statusesCount] => 2309
[utcOffset] => 3600
[languages] => Array (
[0] => de
)
[preferredUsername] => zWDOM
[displayName] => Willi Domroese
[postedTime] => 2009-12-17T01:39:25.000Z
[link] => http://www.twitter.com/zWDOM
[verified] =>
)
[provider] => Array (
[displayName] => Twitter
[link] => http://www.twitter.com
[objectType] => service
)
[twitter_filter_level] => medium
[twitter_entities] => Array (
[urls] => Array (
[0] => Array (
[display_url] => ln.is/paper.li/visua…
[indices] => Array (
[0] => 77
[1] => 99
)
[expanded_url] => http://ln.is/paper.li/visualsucce/7zYNk
[url] => http://www.twitter.com
)
)
[hashtags] => Array ( )
[user_mentions] => Array (
[0] => Array (
[indices] => Array (
[0] => 3
[1] => 17
)
[screen_name] => VisualSuccess
[id_str] => 213337792
[name] => Predrag Gasic
[id] => 213337792
)
[1] => Array (
[indices] => Array (
[0] => 101
[1] => 107
)
[screen_name] => zWDOM
[id_str] => 97334013
[name] => Willi Domroese
[id] => 97334013
)
[2] => Array (
[indices] => Array (
[0] => 108
[1] => 115
)
[screen_name] => Rocket
[id_str] => 870584947
[name] => Rocket Software
[id] => 870584947
)
[3] => Array (
[indices] => Array (
[0] => 116
[1] => 132
)
[screen_name] => JohnKnutson_IBM
[id_str] => 16452310
[name] => John Knutson
[id] => 16452310
)
)
[trends] => Array ( )
[symbols] => Array ( )
)
[twitter_lang] => de
[id] => tag:search.twitter.com,2005:554936456477933569
[retweetCount] => 1
[gnip] => Array (
[urls] => Array (
[0] => Array (
[expanded_url] => http://linkis.com/paper.li/visualsucce/7zYNk
[expanded_status] => 200
[url] => http://www.twitter.com
)
)
[language] => Array (
[value] => de
)
)
[object] => Array (
[postedTime] => 2015-01-13T08:04:48.000Z
[verb] => post
[link] => http://twitter.com/VisualSuccess/statuses/554911928527888384
[generator] => Array (
[displayName] => Linkis.com
[link] => http://linkis.com
)
[body] => "Mainframe & Cloud" Magazine wurde soeben publiziert! http://www.twitter.com ://www.twitter.com
[objectType] => activity
[actor] => Array (
[summary] => Ù† (N), Wirtschaftsinformatiker | SAP Consultant Logistics #bigdata #appdevelopment #webdesign #eCommerce #SocialMedia #contentmarketing #SmartHome #Journal
[image] => https://pbs.twimg.com/profile_images/2841607223/959b0d23646b1f24bd7b70deac160e2f_normal.jpeg
[statusesCount] => 14185
[utcOffset] => 3600
[languages] => Array (
[0] => de
)
[preferredUsername] => VisualSuccess
[displayName] => Predrag Gasic
[postedTime] => 2010-11-08T17:19:27.000Z
[link] => http://www.twitter.com/VisualSuccess
[verified] =>
)
[provider] => Array (
[displayName] => Twitter
[link] => http://www.twitter.com
[objectType] => service
)
[twitter_filter_level] => low
[twitter_entities] => Array (
[urls] => Array (
[0] => Array (
[display_url] => ln.is/paper.li/visua…
[indices] => Array (
[0] => 58
[1] => 80
)
[expanded_url] => http://ln.is/paper.li/visualsucce/7zYNk
[url] => http://www.twitter.com
)
)
[hashtags] => Array ( )
[user_mentions] => Array (
[0] => Array (
[indices] => Array (
[0] => 82
[1] => 88
)
[screen_name] => zWDOM
[id_str] => 97334013
[name] => Willi Domroese
[id] => 97334013
)
[1] => Array (
[indices] => Array (
[0] => 89
[1] => 96
)
[screen_name] => Rocket
[id_str] => 870584947
[name] => Rocket Software
[id] => 870584947
)
[2] => Array (
[indices] => Array (
[0] => 97
[1] => 113
)
[screen_name] => JohnKnutson_IBM
[id_str] => 16452310
[name] => John Knutson
[id] => 16452310
)
)
[trends] => Array ( )
[symbols] => Array (
)
)
)
)
)
Answers to this question would be greatly appreciated
Iterating $insightList will not get you to the cde level. And you don't actually want the cde; you want the message.
Just iterate the tweets. You don't need a foreach to get keyed info from a PHP array.
foreach($insightList['tweets'] as $tweet) {
$insight = $tweet['message']['body'];
if(strlen($insight) > 60) {
$posts[] = array(
'id' => 99999999,
//Temp; remove links from the text
'text' => $insight,
'category' => $insightCategory,
'image' => 'false'
);
}
}
It looks to me from your print_r that what you want is at:
echo $insightList[0]['message']['body'];
When there's a section like this [some_key], then 'some_key' is an associative array key, and you can access those elements be they additional arrays or a value, using the key name, as I illustrated here.

Multidimensional Array PHP Output Values as a row [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is my array
Array
(
[TrackResponse] => Array
(
[Response] => Array
(
[TransactionReference] => Array
(
[CustomerContext] => RocketShipIt
)
[ResponseStatusCode] => 1
[ResponseStatusDescription] => Success
)
[Shipment] => Array
(
[Shipper] => Array
(
[ShipperNumber] => 746354
[Address] => Array
(
[AddressLine1] => 11 PINE ST
[City] => NEW BEDFORD
[StateProvinceCode] => MA
[PostalCode] => 01032 9785
[CountryCode] => US
)
)
[ShipTo] => Array
(
[Address] => Array
(
[City] => FOUNTAIN HILLS
[StateProvinceCode] => AZ
[PostalCode] => 85268
[CountryCode] => US
)
)
[ShipmentWeight] => Array
(
[UnitOfMeasurement] => Array
(
[Code] => LBS
)
[Weight] => 1.00
)
[Service] => Array
(
[Code] => 003
[Description] => GROUND
)
[ShipmentIdentificationNumber] => 746463772264354327
[PickupDate] => 20140709
[DeliveryDateUnavailable] => Array
(
[Type] => Scheduled Delivery
[Description] => Scheduled Delivery Date is not currently available, please try back later
)
[Package] => Array
(
[TrackingNumber] => 746463772264354327
[Activity] => Array
(
[0] => Array
(
[ActivityLocation] => Array
(
[Address] => Array
(
[City] => FOUNTAIN HILLS
[StateProvinceCode] => AZ
[PostalCode] => 85268
[CountryCode] => US
)
[Code] => ML
[Description] => FRONT DOOR
)
[Status] => Array
(
[StatusType] => Array
(
[Code] => D
[Description] => DELIVERED
)
[StatusCode] => Array
(
[Code] => FS
)
)
[Date] => 20140716
[Time] => 142400
)
[1] => Array
(
[ActivityLocation] => Array
(
[Address] => Array
(
[City] => TEMPE
[StateProvinceCode] => AZ
[CountryCode] => US
)
)
[Status] => Array
(
[StatusType] => Array
(
[Code] => I
[Description] => OUT FOR DELIVERY
)
[StatusCode] => Array
(
[Code] => DS
)
)
[Date] => 20140716
[Time] => 041900
)
[2] => Array
(
[ActivityLocation] => Array
(
[Address] => Array
(
[City] => TEMPE
[StateProvinceCode] => AZ
[CountryCode] => US
)
)
[Status] => Array
(
[StatusType] => Array
(
[Code] => I
[Description] => ARRIVAL SCAN
)
[StatusCode] => Array
(
[Code] => AR
)
)
[Date] => 20140715
[Time] => 114500
)
[3] => Array
(
[ActivityLocation] => Array
(
[Address] => Array
(
[City] => HODGKINS
[StateProvinceCode] => IL
[CountryCode] => US
)
)
[Status] => Array
(
[StatusType] => Array
(
[Code] => I
[Description] => DEPARTURE SCAN
)
[StatusCode] => Array
(
[Code] => DP
)
)
[Date] => 20140711
[Time] => 144600
)
[4] => Array
(
[ActivityLocation] => Array
(
[Address] => Array
(
[City] => HODGKINS
[StateProvinceCode] => IL
[CountryCode] => US
)
)
[Status] => Array
(
[StatusType] => Array
(
[Code] => I
[Description] => LOCATION SCAN
)
[StatusCode] => Array
(
[Code] => LC
)
)
[Date] => 20140711
[Time] => 090500
)
[5] => Array
(
[ActivityLocation] => Array
(
[Address] => Array
(
[City] => HODGKINS
[StateProvinceCode] => IL
[CountryCode] => US
)
)
[Status] => Array
(
[StatusType] => Array
(
[Code] => I
[Description] => UNLOAD SCAN
)
[StatusCode] => Array
(
[Code] => UL
)
)
[Date] => 20140711
[Time] => 085300
)
[6] => Array
(
[ActivityLocation] => Array
(
[Address] => Array
(
[City] => HODGKINS
[StateProvinceCode] => IL
[CountryCode] => US
)
)
[Status] => Array
(
[StatusType] => Array
(
[Code] => I
[Description] => ARRIVAL SCAN
)
[StatusCode] => Array
(
[Code] => AR
)
)
[Date] => 20140711
[Time] => 061900
)
[7] => Array
(
[ActivityLocation] => Array
(
[Address] => Array
(
[City] => W SPRINGFIELD
[StateProvinceCode] => MA
[CountryCode] => US
)
)
[Status] => Array
(
[StatusType] => Array
(
[Code] => I
[Description] => DEPARTURE SCAN
)
[StatusCode] => Array
(
[Code] => DP
)
)
[Date] => 20140709
[Time] => 213400
)
[8] => Array
(
[ActivityLocation] => Array
(
[Address] => Array
(
[City] => W SPRINGFIELD
[StateProvinceCode] => MA
[CountryCode] => US
)
)
[Status] => Array
(
[StatusType] => Array
(
[Code] => I
[Description] => ORIGIN SCAN
)
[StatusCode] => Array
(
[Code] => OR
)
)
[Date] => 20140709
[Time] => 183400
)
[9] => Array
(
[ActivityLocation] => Array
(
[Address] => Array
(
[City] => W SPRINGFIELD
[StateProvinceCode] => MA
[CountryCode] => US
)
)
[Status] => Array
(
[StatusType] => Array
(
[Code] => P
[Description] => PICKUP SCAN
)
[StatusCode] => Array
(
[Code] => PU
)
)
[Date] => 20140709
[Time] => 163200
)
[10] => Array
(
[ActivityLocation] => Array
(
[Address] => Array
(
[CountryCode] => US
)
)
[Status] => Array
(
[StatusType] => Array
(
[Code] => M
[Description] => BILLING INFORMATION RECEIVED
)
[StatusCode] => Array
(
[Code] => MP
)
)
[Date] => 20140709
[Time] => 112842
)
)
[PackageWeight] => Array
(
[UnitOfMeasurement] => Array
(
[Code] => LBS
)
[Weight] => 1.00
)
)
)
)
)
I'm looking to access values in the Activity numeric indexed array like such.
foreach($response as $row)
{
foreach($row['Shipment']['Package'] as $k)
{
echo $k['ActivityLocation']['Address']['City'];
}
}
I wanna be able to access the values inside of the numeric keyed array, and print them out in a row 1-10 etc.
The error i'm getting is Fatal error: Cannot use string offset as an array in test.php on line 287
If anybody could help me solve this you would be the bestus!
Please and Thanks
foreach($row['Shipment']['Package'] as $k)
{
echo $k['ActivityLocation']['Address']['City'];
}

Replacing values in array from another array

I have this array structure:
stdClass Object
(
[carrierFsCode] => VX
[flightNumber] => 925
[departureAirportFsCode] => LAX
[arrivalAirportFsCode] => SFO
[stops] => 0
[departureTerminal] => 3
[arrivalTerminal] => 2
[departureTime] => 2014-04-28T07:00:00.000
[arrivalTime] => 2014-04-28T08:20:00.000
[flightEquipmentIataCode] => 32S
[isCodeshare] =>
[isWetlease] =>
[serviceType] => J
[serviceClasses] => Array
(
[0] => F
[1] => J
[2] => Y
)
[trafficRestrictions] => Array
(
)
[codeshares] => Array
(
[0] => stdClass Object
(
[carrierFsCode] => SQ
[flightNumber] => 1407
[serviceType] => J
[serviceClasses] => Array
(
[0] => R
[1] => F
[2] => J
[3] => Y
)
[trafficRestrictions] => Array
(
[0] => Q
)
[referenceCode] => 10594616
)
)
[referenceCode] => 979-1740743--
)
stdClass Object
(
[carrierFsCode] => SQ
[flightNumber] => 1407
[departureAirportFsCode] => LAX
[arrivalAirportFsCode] => SFO
[stops] => 0
[departureTerminal] => 3
[arrivalTerminal] => 2
[departureTime] => 2014-04-28T07:00:00.000
[arrivalTime] => 2014-04-28T08:20:00.000
[flightEquipmentIataCode] => 32S
[isCodeshare] => 1
[isWetlease] =>
[serviceType] => J
[serviceClasses] => Array
(
[0] => R
[1] => F
[2] => J
[3] => Y
)
[trafficRestrictions] => Array
(
[0] => Q
)
[operator] => stdClass Object
(
[carrierFsCode] => VX
[flightNumber] => 925
[serviceType] => J
[serviceClasses] => Array
(
[0] => F
[1] => J
[2] => Y
)
[trafficRestrictions] => Array
(
)
)
[codeshares] => Array
(
)
[referenceCode] => 979-1740743--10594616
)
And this array structure:
Array
(
[0] => stdClass Object
(
[fs] => SQ
[iata] => SQ
[icao] => SIA
[name] => Singapore Airlines
[active] => 1
)
[1] => stdClass Object
(
[fs] => VX
[iata] => VX
[icao] => VRD
[name] => Virgin America
[active] => 1
)
)
Basically what I want to do is take the first array and find its matching IATA/FS code in the second array and replace it with the ICAO code. So for example, with the first array, I want to replace the VX with VRD. I want to be able to apply the same concept to other airline/routes, too...not just VX.
If it helps, I'm getting this information from a JSON return: http://pastebin.com/2w0kQQ26
I looked into array_replace(), but because my PHP skills are almost nothing, I didn't know how to continue.
If someone can point me to the right direction, I'd appreciate it.
With array1 being your first array and array2 being the second array you described.
$comp_arr = array()
foreach ($array2 as $arr) {
$comp_arr[$arr[fs]] = $arr[icao];
}
foreach($array1 as $key => $arr){
if(array_key_exist($arr[carrierFsCode], $comp_arr){
$array1[$key][carrierFsCode] = $comp_arr[$arr[carrierFsCode]];
}
}

PHP multi-dimensional array search for keys and display values

Below is the result of the array from which I want to grab only coordinates and store them in to the one dimensional array.
Array
(
[name] => jackson
[Status] => Array
(
[code] => 200
[request] => geocode
)
[Placemark] => Array
(
[0] => Array
(
[#attributes] => Array
(
[id] => p1
)
[address] => Jackson, MS, USA
[AddressDetails] => Array
(
[#attributes] => Array
(
[Accuracy] => 4
)
[Country] => Array
(
[CountryNameCode] => US
[CountryName] => USA
[AdministrativeArea] => Array
(
[AdministrativeAreaName] => MS
[SubAdministrativeArea] => Array
(
[SubAdministrativeAreaName] => Hinds
[Locality] => Array
(
[LocalityName] => Jackson
)
)
)
)
)
[ExtendedData] => Array
(
[LatLonBox] => Array
(
[#attributes] => Array
(
[north] => 32.3741783
[south] => 32.2232735
[east] => -90.0567509
[west] => -90.3128697
)
)
)
[Point] => Array
(
[coordinates] => -90.1848103,32.2987573,0
)
)
[1] => Array
(
[#attributes] => Array
(
[id] => p2
)
[address] => Jackson, TN, USA
[AddressDetails] => Array
(
[#attributes] => Array
(
[Accuracy] => 4
)
[Country] => Array
(
[CountryNameCode] => US
[CountryName] => USA
[AdministrativeArea] => Array
(
[AdministrativeAreaName] => TN
[SubAdministrativeArea] => Array
(
[SubAdministrativeAreaName] => Madison
[Locality] => Array
(
[LocalityName] => Jackson
)
)
)
)
)
[ExtendedData] => Array
(
[LatLonBox] => Array
(
[#attributes] => Array
(
[north] => 35.7562880
[south] => 35.5402259
[east] => -88.7567579
[west] => -88.9204599
)
)
)
[Point] => Array
(
[coordinates] => -88.8139469,35.6145169,0
)
)
[2] => Array
(
[#attributes] => Array
(
[id] => p3
)
[address] => Jackson, WY, USA
[AddressDetails] => Array
(
[#attributes] => Array
(
[Accuracy] => 4
)
[Country] => Array
(
[CountryNameCode] => US
[CountryName] => USA
[AdministrativeArea] => Array
(
[AdministrativeAreaName] => WY
[SubAdministrativeArea] => Array
(
[SubAdministrativeAreaName] => Teton
[Locality] => Array
(
[LocalityName] => Jackson
)
)
)
)
)
[ExtendedData] => Array
(
[LatLonBox] => Array
(
[#attributes] => Array
(
[north] => 43.4912050
[south] => 43.4578330
[east] => -110.7377220
[west] => -110.8134730
)
)
)
[Point] => Array
(
[coordinates] => -110.7624282,43.4799291,0
)
)
[3] => Array
(
[#attributes] => Array
(
[id] => p4
)
[address] => Jackson, NJ, USA
[AddressDetails] => Array
(
[#attributes] => Array
(
[Accuracy] => 4
)
[Country] => Array
(
[CountryNameCode] => US
[CountryName] => USA
[AdministrativeArea] => Array
(
[AdministrativeAreaName] => NJ
[SubAdministrativeArea] => Array
(
[SubAdministrativeAreaName] => Ocean
[Locality] => Array
(
[LocalityName] => Jackson
)
)
)
)
)
[ExtendedData] => Array
(
[LatLonBox] => Array
(
[#attributes] => Array
(
[north] => 40.1723549
[south] => 39.9990330
[east] => -74.2415390
[west] => -74.4695430
)
)
)
[Point] => Array
(
[coordinates] => -74.3294444,40.1080556,0
)
)
[4] => Array
(
[#attributes] => Array
(
[id] => p5
)
[address] => Jackson, MI, USA
[AddressDetails] => Array
(
[#attributes] => Array
(
[Accuracy] => 4
)
[Country] => Array
(
[CountryNameCode] => US
[CountryName] => USA
[AdministrativeArea] => Array
(
[AdministrativeAreaName] => MI
[SubAdministrativeArea] => Array
(
[SubAdministrativeAreaName] => Jackson
[Locality] => Array
(
[LocalityName] => Jackson
)
)
)
)
)
[ExtendedData] => Array
(
[LatLonBox] => Array
(
[#attributes] => Array
(
[north] => 42.2708699
[south] => 42.2036839
[east] => -84.3568169
[west] => -84.4345460
)
)
)
[Point] => Array
(
[coordinates] => -84.4013462,42.2458690,0
)
)
[5] => Array
(
[#attributes] => Array
(
[id] => p6
)
[address] => Jackson, WI, USA
[AddressDetails] => Array
(
[#attributes] => Array
(
[Accuracy] => 4
)
[Country] => Array
(
[CountryNameCode] => US
[CountryName] => USA
[AdministrativeArea] => Array
(
[AdministrativeAreaName] => WI
[SubAdministrativeArea] => Array
(
[SubAdministrativeAreaName] => Washington
[Locality] => Array
(
[LocalityName] => Jackson
)
)
)
)
)
[ExtendedData] => Array
(
[LatLonBox] => Array
(
[#attributes] => Array
(
[north] => 43.3387369
[south] => 43.3090429
[east] => -88.1422039
[west] => -88.1917450
)
)
)
[Point] => Array
(
[coordinates] => -88.1667599,43.3238919,0
)
)
[6] => Array
(
[#attributes] => Array
(
[id] => p7
)
[address] => Jackson, CA, USA
[AddressDetails] => Array
(
[#attributes] => Array
(
[Accuracy] => 4
)
[Country] => Array
(
[CountryNameCode] => US
[CountryName] => USA
[AdministrativeArea] => Array
(
[AdministrativeAreaName] => CA
[SubAdministrativeArea] => Array
(
[SubAdministrativeAreaName] => Amador
[Locality] => Array
(
[LocalityName] => Jackson
)
)
)
)
)
[ExtendedData] => Array
(
[LatLonBox] => Array
(
[#attributes] => Array
(
[north] => 38.3721550
[south] => 38.3302920
[east] => -120.7489930
[west] => -120.7981980
)
)
)
[Point] => Array
(
[coordinates] => -120.7741018,38.3488023,0
)
)
[7] => Array
(
[#attributes] => Array
(
[id] => p8
)
[address] => Jackson, GA, USA
[AddressDetails] => Array
(
[#attributes] => Array
(
[Accuracy] => 4
)
[Country] => Array
(
[CountryNameCode] => US
[CountryName] => USA
[AdministrativeArea] => Array
(
[AdministrativeAreaName] => GA
[SubAdministrativeArea] => Array
(
[SubAdministrativeAreaName] => Butts
[Locality] => Array
(
[LocalityName] => Jackson
)
)
)
)
)
[ExtendedData] => Array
(
[LatLonBox] => Array
(
[#attributes] => Array
(
[north] => 33.3114890
[south] => 33.2638330
[east] => -83.9354860
[west] => -84.0105969
)
)
)
[Point] => Array
(
[coordinates] => -83.9660209,33.2945651,0
)
)
[8] => Array
(
[#attributes] => Array
(
[id] => p9
)
[address] => Jackson, OH 45640, USA
[AddressDetails] => Array
(
[#attributes] => Array
(
[Accuracy] => 4
)
[Country] => Array
(
[CountryNameCode] => US
[CountryName] => USA
[AdministrativeArea] => Array
(
[AdministrativeAreaName] => OH
[SubAdministrativeArea] => Array
(
[SubAdministrativeAreaName] => Jackson
[Locality] => Array
(
[LocalityName] => Jackson
)
)
)
)
)
[ExtendedData] => Array
(
[LatLonBox] => Array
(
[#attributes] => Array
(
[north] => 39.0669040
[south] => 39.0062730
[east] => -82.5949490
[west] => -82.7069350
)
)
)
[Point] => Array
(
[coordinates] => -82.6365536,39.0520169,0
)
)
[9] => Array
(
[#attributes] => Array
(
[id] => p10
)
[address] => Jackson, MO, USA
[AddressDetails] => Array
(
[#attributes] => Array
(
[Accuracy] => 4
)
[Country] => Array
(
[CountryNameCode] => US
[CountryName] => USA
[AdministrativeArea] => Array
(
[AdministrativeAreaName] => MO
[SubAdministrativeArea] => Array
(
[SubAdministrativeAreaName] => Cape Girardeau
[Locality] => Array
(
[LocalityName] => Jackson
)
)
)
)
)
[ExtendedData] => Array
(
[LatLonBox] => Array
(
[#attributes] => Array
(
[north] => 37.4139659
[south] => 37.3385089
[east] => -89.5972280
[west] => -89.7035499
)
)
)
[Point] => Array
(
[coordinates] => -89.6662063,37.3822732,0
)
)
)
)
//data for single result starts here
Array
(
[Response] => Array
(
[name] => 10121
[Status] => Array
(
[code] => 200
[request] => geocode
)
[Placemark] => Array
(
[#attributes] => Array
(
[id] => p1
)
[address] => Manhattan, NY 10121, USA
[AddressDetails] => Array
(
[#attributes] => Array
(
[Accuracy] => 5
)
[Country] => Array
(
[CountryNameCode] => US
[CountryName] => USA
[AdministrativeArea] => Array
(
[AdministrativeAreaName] => NY
[DependentLocality] => Array
(
[DependentLocalityName] => Manhattan
[PostalCode] => Array
(
[PostalCodeNumber] => 10121
)
)
)
)
)
[ExtendedData] => Array
(
[LatLonBox] => Array
(
[#attributes] => Array
(
[north] => 40.7528519
[south] => 40.7489381
[east] => -73.9917906
[west] => -73.9947563
)
)
)
[Point] => Array
(
[coordinates] => -73.9917906,40.7492821,0
)
)
)
)
//data for single result ends here
I tried the following code for desired results but no success
foreach ($array as $xm) {
foreach ($xm as $points=>$pointkey) {
foreach($pointkey as $cor=>$corkey) {
echo $cor["coordinates"];
}
}
}
it gives me warning "Warning: Invalid argument supplied for foreach() in foreach($pointkey as $cor=>$corkey)"
Try something like:
$coords = array();
foreach ($data['Placemark'] as $entry) { // where $data holds the complete array
$coords[] = $entry['Point']['coordinates'];
}
var_dump($coords);
For only one result you can access the coordinates directly, like:
var_dump($data['Response']['Placemark']['Point']['coordinates']);
I would do something like this:
$coords = array();
array_walk_recursive($input_array, 'get_coords');
function get_coords($item, $key)
{
$coord = ($key === 'coordinates') ? $item : '';
if(!empty($coord))
{
$coords[] = $coord;
}
}
Array
(
[0] => Array
(
[#attributes] => Array
(
[request_id] => 0
[district] =>
[county] => WILTS
[ptc_abs_code] => 58150004231
[house_no] => 232
[post_town] => WESTBURY
[match_status] => 1
[house_name] =>
[postcode] => BA133BN
[surname] =>
[street_2] =>
[street_1] => HIGH ST
)
)
)

Categories