理想情况下,您可以配置 API 以发送 'key' => 'value' 类型对中的内容,尤其是与“时间:状态”相关的“键:值”。不幸的是,我很清楚根据 API 提供者,这可能是不可能的。
所以,如果您完全无法更改 API 的响应,并且您总是得到一个 2n 长的数组,您可以简单地使用 for() 循环或 @987654322 @loop(或任何其他控制结构,实际上)循环遍历数组并使用可用的Increment Operators 之一输出您需要的信息。您还可以使用 this SO answer 中的某些东西将您的数组重新组织成 key:value 对,但是 可能对此有点矫枉过正。
这是一个使用简单的while 循环的简单示例:
// 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';
}
其输出将是:
<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 … -->
如您所见at this sandbox link(点击执行代码按钮查看输出。
最后两件事:
• 您可能想要考虑使用不依赖于left 和right CSS 类的HTML/CSS 结构,例如Grid 或Flexbox,但我输入了一个简单的Ternary Operator 来切换暂时介于两者之间。
• 在该while 循环中,您可能希望验证$api_response[$i] 的每个值是什么类型的数据,以确保您获得预期格式的时间字符串和预期格式的状态.如果出现问题(例如连续有两个时间字符串等),您可以使用 continue 跳过迭代。