PHP explode - running loop through each array item

依然范特西╮ 提交于 2019-12-12 06:58:43

问题


Here's the issue:

I retrieve the following data string from my database:

$row->exceptions = '1,2,3';

After explode I need the below code to check each one of the exploded pieces

$exceptions = explode(",", $row->exceptions);

//result is 
//[0] => 1
//[1] => 2
//[2] => 3

for ($i = 0; $i <= $row->frequency; $i++) {

    if ($exceptions[] == $i) {

        continue;

    } else {

        //do something else
    }
}

How can I make $exceptions[] loop through all keys from the exploded array so it evaluates if ==$i?

Thanks for helping.


回答1:


It should suffice to substitute:

if($exceptions[] == $i)

with:

if(in_array($i,$exceptions))

By the way, it eliminates the need for a nested loop.




回答2:


Ah, should be straightforward, no?

$exceptions = explode(",", $row->exceptions);
for ($i = 0; $i <= $row->frequency; $i++) {

    foreach($exceptions as $j){
    if($j == $i){
        // do something
        break;
    }
}
}



回答3:


I think I understand what you are asking. Here's how you would test within that loop whether the key equals $i.

for ($i = 0; $i <= $row->frequency; $i++)
{
  foreach ($exceptions as $key => $value)
  {
    if ($key == $i)
    {
      continue;
    }
  }
}


来源:https://stackoverflow.com/questions/5925800/php-explode-running-loop-through-each-array-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!