This is my JSON.
Stored in variable named $onceBooking
.
I want to get booking_slots
from each booking
.
This is my code:
for ($i = 0; $i < count($onceBooking); $i++) {
if (count($onceBooking[$i]->bookings) == 0) {
$onceBooking[$i]->total_days = 0;
} else {
$onceBooking[$i]->total_days = count($onceBooking[$i]->bookings);
$bookings = $onceBooking[$i]->bookings;
for ($j = 0; $j < count($bookings); $j++) {
return $bookings[$j]->booking_slots;
}
}
}
But it's returning nothing. Please tell me if I am wrong.
Thanks.
$data = json_decode($onceBooking);
Then you can loop through data to grab your booking objects.
$result = ["total_days" => 0];
foreach($data as $instance) {
$result["total_days"] += count($instance->bookings);
$bookings = $instance->bookings;
for($i = 0; $i < count($bookings); $i++) {
return $bookings->booking_slots;
}
}
-- EDIT: for returning total days & bookings.
$result = ["total_days" => 0, "bookings" => []];
foreach($data as $instance) {
$result["total_days"] += count($instance->bookings);
array_push($result["bookings"], $instance->$bookings);
}
return $result;
You have to modify the code a little bit because you are returning the first element's booking slot.
$data = json_decode($onceBooking);
$bookingSlots = array();
for ($i = 0; $i < count($onceBooking); $i++) {
if (count($onceBooking[$i]->bookings) == 0) {
$onceBooking[$i]->total_days = 0;
} else {
$onceBooking[$i]->total_days = count($onceBooking[$i]->bookings);
$bookings = $onceBooking[$i]->bookings;
for ($j = 0; $j < count($bookings); $j++) {
if (!empty($bookings[$j])) {
$bookingSlots[$bookings[$j]->id] = $bookings[$j]->booking_slots;
}
}
}
}
return $bookingSlots;
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.