Reputation: 117
I want to extract a information from a PHP array based on a given information.
PHP code is
$xmlstring = file_get_contents('file.xml');
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
$HotelCodes = array('BG01I9', 'BG53I4', 'BG23I7');
$code = $HotelCodes[1];
if (!$code) {
throw new Exception("No Hotel Code specified");
}
foreach ($HotelCodes as $code) {
foreach ($hotels as $hotel) {
if (strcasecmp($hotel['HotelCode'], $code) === 0) {
echo "{$hotel['Latitude']}:{$hotel['Longitude']}<br/>";
foreach ($hotel['HotelImages']['ImageUrl'] as $img) {
echo "<img src='{$img}'/><hr/>";
}
break;
}
}
}
print_r $array
with one record is (the array has multiple records):
Array
(
[Hotel] => Array
(
[0] => Array (
[HotelCode] => BG01I9
[Latitude] => 42.6039
[Longitude] => 23.3954
[HotelImages] => Array (
[ImageURL] => Array (
[0] => http://image.metglobal.com/hotelimages/BG01I9/6481077_0x0.jpg
[1] => http://image.metglobal.com/hotelimages/BG01I9/6481092_0x0.jpg
[2] => http://image.metglobal.com/hotelimages/BG01I9/6481109_0x0.jpg
[3] => http://image.metglobal.com/hotelimages/BG01I9/6481139_0x0.jpg
[4] => http://image.metglobal.com/hotelimages/BG01I9/6481163_0x0.jpg
[5] => http://image.metglobal.com/hotelimages/BG01I9/6480990_0x0.jpg
[6] => http://image.metglobal.com/hotelimages/BG01I9/6481002_0x0.jpg
[7] => http://image.metglobal.com/hotelimages/BG01I9/6481015_0x0.jpg
[8] => http://image.metglobal.com/hotelimages/BG01I9/6481033_0x0.jpg
[9] => http://image.metglobal.com/hotelimages/BG01I9/6481058_0x0.jpg
)
)
)
)
And i want to echo the Hotel Images, Latitude and Longitude based on the HotelCodes given by me:
The hotel code is $HotelCodes[0]
The error received is :
Fatal error: Uncaught exception 'Exception' with message 'No Hotel Code specified' in /home/truckass/public_html/site/test/teste.php:10 Stack trace: #0 {main} thrown in /home/truckass/public_html/siteo/test/teste.php on line 10
I need to echo for HotelCodes[1]
$img[1][0] ....$img[1][5]
$Latitude[1]
$Longitude[1]
Could you please assist.
Upvotes: 1
Views: 57
Reputation: 7597
This is the mistake:
$HotelCodes[] = array('BG01I9', 'BG53I4', 'BG23I7');
You should omit the first brackets:
$HotelCodes = array('BG01I9', 'BG53I4', 'BG23I7');
You can now access the second code by using $HotelCodes[1]
.
In your snippet, you created an array with an array. That in itself is perfectly valid, but then you should access the value by using $HotelCodes[0][1]
.
If you wanna stick with the square brackets, you can do this (>= 5.4):
$HotelCodes = ['BG01I9', 'BG53I4', 'BG23I7'];
Upvotes: 1