【问题标题】:PHP loop for array on the basis of index numbers基于索引号的数组的PHP循环
【发布时间】:2021-02-27 23:42:55
【问题描述】:

我从 Order tracking api 得到一个数组作为输出,它的值以偶数变化,例如有时它包含 2 个值,有时它包含 4 个,有时是 6 个或 8 个。

例如

$array = array(time1,status1);

有时

$array = array(time1,status1,time2,status2);

或者

$array = array(time1,status1,time2,status2,time3,status3);

所以我在做什么,我有一个时间表来显示订单状态。 这是它的代码

<div class="timeline">
  <div class="container left">
    <div class="content">
      <h2>time</h2>
      <p>status</p>
    </div>
  </div>
  <div class="container right">
    <div class="content">
      <h2>time</h2>
      <p>status</p>
    </div>
  </div>
</div>

所以我想要的是在 php 中创建一个循环,以在 h2 标签中显示时间(奇数索引值)和在 p 标签中显示状态(偶数索引值)

数组中值的数量可能会有所不同,所以我想要一个循环来为每次创建时间线及其相应的状态。

【问题讨论】:

  • 如果可能,您应该改为更改 API 输出数据的方式。这种格式没有意义。

标签: php html arrays loops


【解决方案1】:

理想情况下,您可以配置 API 以发送 'key' =&gt; '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(点击执行代码按钮查看输出。

最后两件事:

• 您可能想要考虑使用不依赖于leftright CSS 类的HTML/CSS 结构,例如GridFlexbox,但我输入了一个简单的Ternary Operator 来切换暂时介于两者之间。

• 在该while 循环中,您可能希望验证$api_response[$i] 的每个值是什么类型的数据,以确保您获得预期格式的时间字符串和预期格式的状态.如果出现问题(例如连续有两个时间字符串等),您可以使用 continue 跳过迭代。

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 2012-01-01
    • 1970-01-01
    • 2012-08-15
    相关资源
    最近更新 更多