如果存在则循环遍历数组?

时间:2016-01-12 19:50:08

标签: php

我有两个数组:

$qa_content['form']['fields']
$qa_content['form_q_edit']['fields']

其中一个或零个最多同时存在。我想循环存在一个。

我可以这样做:

if isset($qa_content['form_q_edit']['fields']){
  loop($qa_content['form_q_edit']['fields'])
}elseif (isset $qa_content['form_q_edit']['fields']{
  loop($qa_content['form_q_edit']['fields'])
}

但有没有一种更清洁/更聪明的方式,可能是通过合并它们或什么?

2 个答案:

答案 0 :(得分:0)

如果循环函数对两个数组进行相同的操作,则将它们合并,然后调用循环函数,如下所示:

$merge= array_merge($qa_content['form_q_edit']['fields'], $qa_content['form_q_edit']['fields']);
if($all){
 loop($merge);
}

答案 1 :(得分:0)

这取决于数组的处理是否相同。如果是这样,最好的优化就是不复制循环中更复杂的处理逻辑。例如,如果循环中的处理相同,那么最好只有一次循环处理逻辑:

$myArr = NULL;

if isset($qa_content['form_q_edit']['fields']){
  $myArr = $qa_content['form_q_edit']['fields'];
}elseif (isset $qa_content['form_q_edit']['fields']){
  $myArr = $qa_content['form_q_edit']['fields'];
}

if(!is_null($myArr))
{
  loop($myArr)
  {
    //do common processing here
  }
}
相关问题