【问题标题】:How can I start foreach command from specific moment?如何从特定时刻开始 foreach 命令?
【发布时间】:2023-03-14 18:16:02
【问题描述】:

我为我的网站使用 XML 导入。主要问题是执行时间和我的服务器强制执行的限制。因此,我想将 XML 导入拆分为段。到目前为止,我的脚本看起来是这样的:

$xml = simplexml_load_file('test.xml');

foreach ($xml->products as $products) {

...

}

问题是如何从特定时刻开始 foreach 命令,例如foreach 可以从 100 开始。我知道可以在下面这样完成,但是有没有更简单的方法?

$n=0;
foreach ($xml->products as $products) {
$n++;
if ($n>99) { //do something }
else { //skip }

}

【问题讨论】:

标签: php xml foreach


【解决方案1】:

只需使用 for 循环,即可指定要循环的范围

for($i = 100; $i < 200; $i++)
{
//do something
}

【讨论】:

  • 这是个好主意,从 100 到 200,但我想要从 100 到 $xml->products 中所有值的末尾。那么有一种方法可以知道 $xml->products 有多少个值?因为例如如果 $xml->products 以 110 结束,那么 90 次循环将是空的。
  • 是的,你可以,让它for($i=100; $i &lt; count($xml-&gt;products); $i++)
  • 谢谢@Naryl - 现在答案已经完成。这是我一直在寻找的。​​span>
【解决方案2】:

您可以像其他人建议的那样使用for 或while,或者如果必须是foreach,您可以使用continue:

$n=0; //you have to do this outside or it won't work at all.
$min_value=100;
foreach ($xml->products as $products) {
    $n++;
    if ($n<=$min_value) { continue; } //this will exit the current iteration, check the bool in the foreach and start the next iteration if the bool is true. You don't need a else here.

    //do the rest of the code
}

【讨论】:

  • 感谢这个想法,“继续”命令以后对我有用。我认为你之前提到的“for”和“count”对于我的 php 脚本可能更好。
  • continue 通常更有用,当您想要跳过遵循其他条件的特定元素时,它们的顺序,例如具有等于值的 id 或具有空元素等的元素。
猜你喜欢
  • 1970-01-01
  • 2018-12-23
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
相关资源
最近更新 更多