I've had to ask this one again, sorry, but I'm having a problem trying to process this array. I have tried several different ways but none where right, here's the array:
Array (
[search] => Array (
[response] => Array (
[errors] =>
[number_of_hotels] => 1 of 1
)
[lr_rates] => Array (
[hotel] => Array (
[hotel_ref] => 3116
[hotel_currency] => [U] => USD
[hotel_rooms] => Array (
[room] => Array (
[ref] => 6382
[type] => 1
[type_description] => Standard
[sleeps] => 8
[rooms_available] =>
[adults] => 8
[children] =>
[breakfast] => false
[dinner] => false
[description] =>
[alternate_description] =>
[rack_rate] => 82.01
[date] => 19/08/201220/08/201221/08/2012
[numeric_hotelcurrencyprice] => FullFullFull
[formatted_date] => 19 August 201220 August 201221 August 2012
[price] => FullFullFull
[hotelcurrencyprice] => FullFullFull
[numeric_price] => FullFullFull
[requested_currency] => GBPGBPGBP
[numeric_hotelcurrencyprice] => FullFullFull
[available_online] => false
[minimum_nights] => 1
[bed_type] =>
[cancellation_policy] =>
[cancellation_days] =>
[cancellation_hours] =>
[room_terms] =>
)
[room] => Array (
[ref] => 6382
[type] => 1
[type_description] => Standard
[sleeps] => 8
[rooms_available] =>
[adults] => 8
[children] =>
[breakfast] => false
[dinner] => false
[description] =>
[alternate_description] =>
[rack_rate] => 82.01
[date] => 19/08/201220/08/201221/08/2012
[numeric_hotelcurrencyprice] => FullFullFull
[formatted_date] => 19 August 201220 August 201221 August 2012
[price] => FullFullFull
[hotelcurrencyprice] => FullFullFull
[numeric_price] => FullFullFull
[requested_currency] => GBPGBPGBP
[numeric_hotelcurrencyprice] => FullFullFull
[available_online] => false
[minimum_nights] => 1
[bed_type] =>
[cancellation_policy] =>
[cancellation_days] =>
[cancellation_hours] =>
[room_terms] =>
)
)
[cancellation_type] => First Night Stay Chargeable
[cancellation_policy] => 2 Days Prior to Arrival
[CityTax] => Array (
[TypeName] =>
[Value] =>
[OptedIn] =>
[IsCityTaxArea] =>
)
)
)
)
)
Ok, I need to traverse the array and create a loop, so for every instance of ROOM it will repeat the process. Then i need to extract the data from room array and use it to populate rows in MySQL for each instance of room.
This is the code I have so far which prints the names and values in the room array. However, it only gets one of the room arrays. What can I do to read all of the rooms? I am also thinking this is too many for-each but don't seem to be able to traverse down ['']['']['']...
or by just using the associative name.
foreach($arr['search'] as $lr_rates) {
foreach($lr_rates['hotel'] as $hotel) {
foreach($hotel['room'] as $field => $value){
print $field;print $value;
}
}
}
It might also be worth mentioning the values in these arrays are always fluctuating.
I think you can really simplify this quote a bit. If you know that this will always be the structure then you can jump right down into the hotels and then into the rooms.
foreach($arr['search']['lr_rates']['hotel'] as $hotel) {
// You can access all of the keys in the hotel array here
foreach($hotel['hotel_rooms'] as $room) {
// Do stuff with the room array
}
}
I would recommend either building your insert script on the fly and calling the database just once for the write, or if you are updating then using a transaction. As the number of rooms gets larger you will slow your script down with a bunch of writes to disk.
the formatting of your data's output is very bad and unreadable. I cannot really identify what you are trying to do.
possibility: the inner array [hotel_rooms] => Array () uses the key room multiple times. as array keys are unique, you overwrite the data at the index room. this is why you only get one room.
possibility: there are rooms inside a room -> use a recursive function to iterate over all rooms like this:
function handleRoom(array $room) {
// do something with $room
if (array_key_exists('room', $room)) {
handleRoom($room['room']);
}
}
$room = array(
'some' => 'room',
'data' => 'and another',
'room' => array(
'is' => 'inside',
'of the' => 'main room',
),
);
handleRoom($room);
Related
Ok, this question was probably asked many times here. Tried searching for a way that works but I dont find the correct term to search it.
I have following 2 array
Array 1
Array
(
[1] => Array
(
[data] => DFF022
)
[2] => Array
(
[data] => DFF026
)
)
Array 2
Array
(
[0] => Array
(
[number] => INC0000002
[ia] =>
[description] => Printer not working
[state] => Monitoring - Waiting for Client
[updated] => 12/30/2020 19.09.01
[opened] => 12/24/2020 20.35.36
)
[1] => Array
(
[number] => INC0000003
[ia] =>
[description] => Monitor broke down
[state] => Pending - Awaiting Change Approval/Implementation
[updated] => 12/29/2020 23.57.06
[opened] => 12/29/2020 08.21.38
)
)
Now the number of item inside the array is always will be same. If array 1 got 10 items, then array 2 will have 10 items as well.
I'm looking a way to merge the array to something like this
Array
(
[0] => Array
(
[number] => INC1879727
[ia] =>
[description] => Unable to replay CME NS message
[state] => Monitoring - Waiting for Client
[updated] => 12/30/2020 19.09.01
[opened] => 12/24/2020 20.35.36
[data] => DFF022
)
[1] => Array
(
[number] => INC1884171
[ia] =>
[description] => mw_uat - UAT00MSV_LNP6_01_pga_aggregate_limit
[state] => Pending - Awaiting Change Approval/Implementation
[updated] => 12/29/2020 23.57.06
[opened] => 12/29/2020 08.21.38
[data] => DFF026
)
)
Any idea on how to accomplish this?
Using array merge or combine just combines the array and I have double the items I wanted.
You can run a foreach() to inject the data. To directly modify array elements of $arr2 within the loop we precede $value with &, so the value is assigned by reference:
<?php
$arr1 = [
['data' => 'DFF022',],
['data' => 'DFF026',],
];
$arr2 = [
[
'number' => 'INC0000002',
'ia' => '',
'description' => 'Printer not working',
'state' => 'Monitoring - Waiting for Client',
'updated' => '12/30/2020 19.09.01',
'opened' => '12/24/2020 20.35.36',
],
[
'number' => 'INC0000003',
'ia' => '',
'description' => 'Monitor broke down',
'state' => 'Pending - Awaiting Change Approval/Implementation',
'updated' => '12/29/2020 23.57.06',
'opened' => '12/29/2020 08.21.38',
],
];
foreach($arr2 as $key => &$value) {
$value['data'] = $arr1[$key]['data'];
}
Output (print_r($arr2)):
Array
(
[0] => Array
(
[number] => INC0000002
[ia] =>
[description] => Printer not working
[state] => Monitoring - Waiting for Client
[updated] => 12/30/2020 19.09.01
[opened] => 12/24/2020 20.35.36
[data] => DFF022
)
[1] => Array
(
[number] => INC0000003
[ia] =>
[description] => Monitor broke down
[state] => Pending - Awaiting Change Approval/Implementation
[updated] => 12/29/2020 23.57.06
[opened] => 12/29/2020 08.21.38
[data] => DFF026
)
)
working demo
First off, I'm new to PHP and coding in general, so this might be quite an obvious answer.
I'm currently working with the Strava API, and I'm trying to extract data from an Array/Object which is the result of the following API call:
$recentactivities = $api->get('athlete/activities', array('per_page' => 100));
which returns:
Array (
[1] => stdClass Object (
[id] => XXXX
[resource_state] => 2
[external_id] => XXXX
[upload_id] => XXXX
[athlete] => stdClass Object (
[id] => XXXX
[resource_state] => 1
)
[name] => Let\'s see if I can remember how to do this cycling malarkey...
[distance] => 11858.3
[moving_time] => 1812
[elapsed_time] => 2220
[total_elevation_gain] => 44
[type] => Ride
[start_date] => 2014-07-12T13:48:17Z
[start_date_local] => 2014-07-12T14:48:17Z
[timezone] => (
GMT+00:00
) Europe/London
[start_latlng] => Array (
[0] => XXXX
[1] => XXXX
)
[end_latlng] => Array (
[0] => XXXX
[1] => -XXXX
)
[location_city] => XXXX
[location_state] => England
[location_country] => United Kingdom
[start_latitude] => XXXX
[start_longitude] => XXXXX
[achievement_count] => 4
[kudos_count] => 1
[comment_count] => 0
[athlete_count] => 1
[photo_count] => 0
[map] => stdClass Object (
[id] => a164894160
[summary_polyline] => XXXX
[resource_state] => 2
)
[trainer] =>
[commute] =>
[manual] =>
[private] =>
[flagged] =>
[gear_id] => b739244
[average_speed] => 6.544
[max_speed] => 10.8
[average_cadence] => 55.2
[average_temp] => 29
[average_watts] => 99.3
[kilojoules] => 179.9
[device_watts] =>
[average_heartrate] => 191.2
[max_heartrate] => 200
[truncated] =>
[has_kudoed] =>
)
This repeats for the most recent activities.
I'm attempting to extract average_heartrate, which I can do for a single object using the following:
$recentactivities[1]->average_heartrate;
but I'd like to extract all instances of average_heartrate from the Array. I've tried to use a foreach statement, but to be honest, I have no idea where to start.
Any help would be much appreciated.
It's actually pretty simple you can indeed use a foreach loop:
foreach($myArray as $obj){
//$obj is an object so:
if(isset($obj->average_heartrate)){
echo $obj->average_heartrate;
}
}
With this code you iterate through your array with objects and save the wanted array within an array so you can work further with it.
$heartrateArray = array(); // create a new array
//iterate through it with an foreach
foreach($recentactivities as $activity){
// save the average_heartrate as a value under a new key in the array
$heartrateArray[] = $activity->average_heartrate;
}
I am fairly new to PHP and I am writing a PHP function that grabs an object from SOAP.
I found a code to convert it to an array but I can't manage to echo any data.
The array from print_r
Array
(
[Status] => Array
(
[Code] => 0
[Message] => OK
)
[Order] => Array
(
[OrderNumber] => 9334543
[ExternalOrderNumber] =>
[OrderTime] => 2014-07-15T15:20:31+02:00
[PaymentMethod] => invoice
[PaymentStatus] => Paid
[ShipmentMethod] => Mypack
[DeliveryStatus] => Delivered
[Language] => sv
[Customer] => Array
(
[CustomerId] => 13556
[CustomerNumber] =>
[Username] => admin
[Approved] => 1
[OrgNumber] => 9309138445
[Company] =>
[VatNumber] =>
[FirstName] => Jane
[LastName] => Doe
[Address] => Gatan
[Address2] =>
[Zip] => 1230
[City] => Staden
[Country] => Sweden
[CountryCode] => SE
[PhoneDay] => 84848474
[PhoneNight] =>
[PhoneMobile] =>
[Email] => mail#msn.com
[NewsLetter] =>
[OrgType] => person
[OtherDelivAddress] =>
[DelivName] =>
[DelivAddress] =>
[DelivAddress2] =>
[DelivZip] =>
[DelivCity] =>
[DelivCountry] =>
[DelivCountryCode] =>
)
[Comment] =>
[Notes] => 9063025471 UK/MA
[CurrencyCode] => SEK
[ExchangeRate] => 1
[LanguagePath] => se
[FreightWithoutVat] => 0
[FreightWithVat] => 0
[FreightVatPercentage] => 25
[PayoptionFeeWithoutVat] => 0
[PayoptionFeeWithVat] => 0
[PayoptionFeeVatPercentage] => 25
[CodWithoutVat] => 0
[CodWithVat] => 0
[CodVatPercentage] => 0
[DiscountWithoutVat] => 0
[DiscountWithVat] => 0
[DiscountVat] => 0
[TotalWithoutVat] => 4388
[TotalWithVat] => 5485
[TotalVat] => 1097
[PayWithoutVat] =>
[AffiliateCode] =>
[AffiliateName] =>
[OrderField] => Array
(
[0] => Array
(
[Name] => external_ref
[Value] => 43445
)
[1] => Array
(
[Name] => webshopid
[Value] => 423
)
[2] => Array
(
[Name] => webshopname
[Value] => Manuell
)
)
)
)
Non working code
echo $array[1][0]
I have tried different combos of indexes. I know how to return the values from the soap object but if I could do it this way it would be easier. It should work shouldn't it?
$array[1] is the second index of the array. the key of this array us "Status", this array contains a code and message
i assume you want to echo the message, you can do that with the following
echo $array[1]["Status"]["Message"];
You should use $array['Status']['Code'] , $array['Status']['Message'], $array['Order']['OrderNumber'], $array['Order']['Customer']['CustomerId'] and so on to display your data. It's an associative array so you need to use string keys and not numbers
try
$array['Order']['Customer']['LastName']
is my best guess without losing my sanity in that one line.
But for us to be sure please post the print_r($array) output
There are some way I always do this:
print_r($array);
And the other way is
$array[0]['Order']['LastName']
Try to access the arrays elements with the string keys, not the integer ones you are using:
echo $array['Order']['Customer']['Address'];
Another way you could see what is going on is by iterating through the array, and print out the keys and values:
foreach ($array as $key => $value)
echo "Key=$key value=$value<br>";
im having a problem trying to process this array tried several different ways but none where right, here's the array
Array (
[search] => Array (
[response] => Array (
[errors] =>
[number_of_hotels] => 1 of 1
)
[lr_rates] => Array (
[hotel] => Array (
[hotel_ref] => 3116
[hotel_currency] => [U] => USD
[hotel_rooms] => Array (
[room] => Array (
[ref] => 6382
[type] => 1
[type_description] => Standard
[sleeps] => 8
[rooms_available] =>
[adults] => 8
[children] =>
[breakfast] => false
[dinner] => false
[description] =>
[alternate_description] =>
[rack_rate] => 82.01
[date] => 19/08/201220/08/201221/08/2012
[numeric_hotelcurrencyprice] => FullFullFull
[formatted_date] => 19 August 201220 August 201221 August 2012
[price] => FullFullFull
[hotelcurrencyprice] => FullFullFull
[numeric_price] => FullFullFull
[requested_currency] => GBPGBPGBP
[numeric_hotelcurrencyprice] => FullFullFull
[available_online] => false
[minimum_nights] => 1
[bed_type] =>
[cancellation_policy] =>
[cancellation_days] =>
[cancellation_hours] =>
[room_terms] =>
)
[room] => Array (
[ref] => 6382
[type] => 1
[type_description] => Standard
[sleeps] => 8
[rooms_available] =>
[adults] => 8
[children] =>
[breakfast] => false
[dinner] => false
[description] =>
[alternate_description] =>
[rack_rate] => 82.01
[date] => 19/08/201220/08/201221/08/2012
[numeric_hotelcurrencyprice] => FullFullFull
[formatted_date] => 19 August 201220 August 201221 August 2012
[price] => FullFullFull
[hotelcurrencyprice] => FullFullFull
[numeric_price] => FullFullFull
[requested_currency] => GBPGBPGBP
[numeric_hotelcurrencyprice] => FullFullFull
[available_online] => false
[minimum_nights] => 1
[bed_type] =>
[cancellation_policy] =>
[cancellation_days] =>
[cancellation_hours] =>
[room_terms] =>
)
)
[cancellation_type] => First Night Stay Chargeable
[cancellation_policy] => 2 Days Prior to Arrival
[CityTax] => Array (
[TypeName] =>
[Value] =>
[OptedIn] =>
[IsCityTaxArea] =>
)
)
)
)
)
ok i need to traverse the array and create a loop so for every instance of room it will repeat the process then i need to extract the data from room array and use it to populate rows in MySQL there will be multiple instances of room this is the code i have so far which prints the names and values in the room array but it only gets one of the room arrays what can i do to set it up to read them all and i am also thinking this is too many for-each but don't seem to be able to traverse down ['']['']['']...
or by just using the associative name.
foreach($arr['search'] as $lr_rates) {
foreach($lr_rates['hotel'] as $hotel) {
foreach($hotel['room'] as $field => $value){
print $field;print $value;
}
}
}
it mite also be worth mentioning the values in these arrays are always fluctuating
you don't have to use so much foreach loops in your script as it not looks good. this is an associative array.
you can simply access associate array by using its keys. do some google for it.you can find many scripts on this.
foreach($arr as $search) {
foreach($search as $lr_rates) {
foreach($lr_rates as $hotel) {
foreach($hotel as $hotel_rooms) {
print_r($hotel_rooms['room'])
}
}
}
}
EDIT: These many foreach loops are just to make understand how to reach to room. You can also get the result directly ofcourse.
print_r($arr['search']['lr_rates']['hotel']['hotel_rooms']['room']);
I want to create something like the following array
[Schedule_Date_Group] => Array
(
[Schedule_Date] => Array
(
[Friday, September 16, 2011] => Array
(
[Schedule_Item] => Array
(
[nid] => 763
[time] => 1:15 PM
[title] => What a Publisher Does: 5 Reasons Why You Need a...
[event_type] => events
[length] =>
[movie_type] =>
[details] =>
)
[Schedule_Item] => Array
(
[nid] => 763
[time] => 1:15 PM
[title] => What a Publisher Does: 5 Reasons Why You Need a...
[event_type] => events
[length] =>
[movie_type] =>
[details] =>
)
)
)
)
But I have a few issues, first the array seems to be getting created with a preceding # for the first value. Example
[7] => Array
(
[Schedule_Date_Group] => Array
(
And my arrays are not pushing it under the Date Array ([Friday, September 16, 2011] => Array) They are just being added to the end as a normal array. Example
[7] => Array
(
[Schedule_Date_Group] => Array
(
[Schedule_Date] => Array
(
[Friday, September 16, 2011] => Array
(
[Schedule_Item] => Array
(
[nid] => 763
[time] => 1:15 PM
[title] => What a Publisher Does: 5 Reasons Why You Need a...
[event_type] => events
[length] =>
[movie_type] =>
[details] =>
)
)
)
)
)
[8] => Array
(
[Schedule_Item] => Array
(
[nid] => 764
[time] => 1:30 PM
[title] => Navigating the Road to Licensing Music For Your...
[event_type] => events
[length] =>
[movie_type] =>
[details] =>
)
)
How can I fix these two issues. They are again, #'s preceding the Schedule_Date_Group array and the sub arrays being added to the end rather then nested under the date group array.
PHP For the main schedule item and date group part
$xml[] = array("Schedule_Date_Group" => array("Schedule_Date" => array($pretty_date => array("Schedule_Item" => array("nid" => $do['nid'], "time" => $pretty_time, "title" => $title, "event_type" => $do['field_event_type_value'], "length" => $do['field_length_value'], "movie_type" => $do['field_movie_type_value'], "details" => $schedule_details)))));
PHP for the sub menu items
$xml[] = array("Schedule_Item" => array("nid" => $do['nid'], "time" => $pretty_time, "title" => $title, "event_type" => $do['field_event_type_value'], "length" => $do['field_length_value'], "movie_type" => $do['field_movie_type_value'], "details" => $schedule_details));
It is being looped through so there is no way for me to just create a giant array. And if a new "Schedule Date" is set it will create a new [Schedule_Date_Group] => Array
(
[Schedule_Date] => Array
(
[Friday, September 16, 2011] => Array
(
and all the sub content should go under that new one.
So I would end up with
DATE
- Schedule_Item 1
- Schedule_Item 2
- Schedule_Item 3
- Schedule_Item 4
New Date
- Schedule Item 5
- Schedule Item 6
etc...
Any help?
Firstly, using a huge array to manually generate some XML like this is not the way to do it. Use something like XMLWriter or DOM instead, then you can build your document on the fly as you obtain your data. However, if you really want to, or are forced to do it like this, read on...
Secondly, what you are trying to do cannot be done. This is because you want use the same array key for multiple entries which won't work - you will just end up overwriting your previous entry.
Thirdly, your numeric keys are appearing because you are using $xml[] (array_push() behaves in the same way) and it will always add a numeric key because you have not told it what you want your text key to be.
Fourthly, your extra items are being added to the outer level of the array because that is what you have told PHP to do. $xml[] will always add a new key to the outer level of the $xml variable because you have not told PHP you are dealing with an inner array.
Your structure needs to be more like this:
$scheduleDateGroup = array (
'Friday, September 16, 2011' => array (
// These are your schedule items...
0 => array( ... ),
1 => array( ... ),
2 => array( ... ),
...
),
'Saturday, September 17, 2011' => array (
0 => array( ... ),
1 => array( ... ),
2 => array( ... ),
...
),
...
);
...and you can push new items onto specific days like this:
$scheduleDateGroup[$date][] = array( ... );
Then you can loop through it and turn it into XML with something like this:
echo "<Schedule_Date_Group>\n";
foreach ($scheduleDateGroup as $day => $schedules) {
echo " <Schedule_Date date=\"$day\">\n";
foreach ($schedules as $item) {
echo " <Schedule_Item";
foreach ($item as $attr => $value) echo " $attr=\"$value\"";
echo " />\n";
}
echo " </Schedule_Date>\n";
}
echo "</Schedule_Date_Group>";