I have an array that looks like this:
Array ( [0] => stdClass Object ( [message] => Out for delivery [date] => 07/06/2022 [time] => 10:30:12 AM ) [1] => stdClass Object ( [message] => Consolidation arrived at gateway [date] => 07/06/2022 [time] => 8:00:07 AM ) [2] => stdClass Object ( [message] => Departed sort facility [date] => 07/06/2022 [time] => 6:30:07 AM ) [3] => stdClass Object ( [message] => Arrived at sort facility [date] => 07/06/2022 [time] => 12:15:05 AM ) [4] => stdClass Object ( [message] => Departed sort facility [date] => 06/06/2022 [time] => 10:00:06 PM ) [5] => stdClass Object ( [message] => Driver collected [date] => 06/06/2022 [time] => 4:45:07 PM ) [6] => stdClass Object ( [message] => Label created [date] => 06/06/2022 [time] => 12:52:27 PM ) )
I have a variable for the progress of a bar
$progress = '0.25';
I am trying to set the progress of the bar based on whether either of the below tracking updates is present in the array. Of course, because multiple of the IF statements could return TRUE because all of those tracking updates could be present in the array, the code is not setting $progress correctly. Any ideas on how to solve this so that the correct value is set for $progress?
foreach($events as $item) {
if ($item->message == "POD"){
$progress = '1';
}
if ($item->message == "Out for delivery"){
$progress = '0.75';
}
if ($item->message == "Departed sort facility"){
$progress = '0.5';
}
if ($item->message == "Driver collected"){
$progress = '0.25';
}
}
CodePudding user response:
If we could consider a 1-1 relation between each step and progress. What about this:
$steps = [
'Out for delivery',
'Consolidation arrived at gateway',
'Out for delivery',
'Consolidation arrived at gateway',
'Departed sort facility ',
'Arrived at sort facility ',
'Departed sort facility ',
'Driver collected',
'Label created',
];
$steps_count = 0;
foreach ($events as $item) {
if (in_array($item->message, $steps)) {
$steps_count ;
}
}
$progress = $steps_count / count($steps);
CodePudding user response:
Exiting the loop via break;
once a tracking update has been found works:
foreach($events as $item) {
if ($item->message == "POD"){
$progress = '1';
break;
}
if ($item->message == "Out for delivery"){
$progress = '0.75';
break;
}
if ($item->message == "Departed sort facility"){
$progress = '0.5';
break;
}
if ($item->message == "Driver collected"){
$progress = '0.25';
break;
}
}