Ideally, you'd be able to configure the API to send out something in a 'key' => 'value'
type pair, especially something as "key : value" related as "time : status". Unfortunately, I'm well aware that depending on the API provider, this may not be possible.
So, provided that you can't change the API's response at all, and you always just get an array that's 2n
long, you can simply use a for()
loop or while
loop (or any other control structure, really) to loop through the array and output the information you need with one of the Increment Operators available. You could also make use of something from this SO answer to reorganize your array into key:value
pairs, but that may be overkill for this.
Here's a simple example using a simple while
loop:
// Sample API Response (unsure of format, so Unix Timestamp + Text Status)
$api_response = array(
1605552893, 'Processing',
1605451893, 'Pending',
1605350893, 'Complete',
1605250893, 'Complete',
1605150893, 'Complete',
1605050893, 'Complete'
);
// Define some starting variables
$i = 0; // Start a counter at 0
$n = count($api_response); // Store length as a variable
$side = 'left'; // Set the first directional side
// Proceed to loop through the response
while( $i < $n ){
/**
* This is the iterable HTML block
*
* We use the Post-Increment operator ($i++) to
* get the current index [0] and then bump it up
* to [1] automatically. This gives us [0][1] in
* the first iteration, [2][3] in the second, etc
*/
printf( '<div class="content %s">
<h2>%s</h2>
<p>%s</p>
</div>', $side, date('M jS, D', $api_response[$i++]), $api_response[$i++]);
// Set side to the opposite of current side
if( $i % 2 === 0 )
$side = ($side=='left') ? 'right' : 'left';
}
The output of which would be:
<div class="content left">
<h2>Nov 16th, Mon</h2>
<p>Processing</p>
</div>
<div class="content right">
<h2>Nov 15th, Sun</h2>
<p>Pending</p>
</div>
<div class="content left">
<h2>Nov 14th, Sat</h2>
<p>Complete</p>
</div>
<!-- … etc … -->
As you can see at this sandbox link (click on the Execute Code button to see the output.
Two final things:
• You may want to consider using an HTML/CSS structure that doesn't rely on left
and right
CSS classes like Grid or Flexbox, but I put in a simple Ternary Operator to switch between the two for you for now.
• In that while
loop, you may want to validate what type of data each value of $api_response[$i]
is, to make sure that you're getting a time string in your expected format, and status in your expected format. You can use continue
to skip the iteration if something is wrong (like you got two time strings in a row or something).