仅当函数存在并且不为空时,将数组包括在函数中



我有一个函数来洗牌几个数组并返回一个长数组:

function array_zip_merge() {
  $output = array();
  // The loop incrementer takes each array out of the loop as it gets emptied by array_shift().
  for ($args = func_get_args(); count($args); $args = array_filter($args)) {
    // &$arg allows array_shift() to change the original.
    foreach ($args as &$arg) {
      $output[] = array_shift($arg);
    }
  }
  return $output;
}

im这样运行:

$visirezai = array_zip_merge($tretiRezai, $ketvirtiRezai, $sphinxorezaiclean);

问题有时是一个,两个甚至所有数组是空的或根本不设置的,我会收到这样的循环错误消息:

Notice: Undefined variable: sphinxorezaiclean in /usr/share/nginx/search.php on line 177
Warning: array_shift() expects parameter 1 to be array, boolean given in /usr/share/nginx/search.php on line 148
Warning: array_shift() expects parameter 1 to be array, boolean given in /usr/share/nginx/search.php on line 148
Warning: array_shift() expects parameter 1 to be array, null given in /usr/share/nginx/search.php on line 148
Warning: array_shift() expects parameter 1 to be array, boolean given in /usr/share/nginx/search.php on line 148
Warning: array_shift() expects parameter 1 to be array, boolean given in /usr/share/nginx/search.php on line 148
Warning: array_shift() expects parameter 1 to be array, boolean given in /usr/share/nginx/search.php on line 148

第177行是$visirezai = array_zip_merge($tretiRezai, $ketvirtiRezai, $sphinxorezaiclean);所在的位置(我知道Sphinxorezaiclean根本不是设置,但有时是这样的(和第148行 - 函数array_zip_merge是。

它继续这样,直到我停止在浏览器中加载网页。

我解决这个问题的方法是这样的:首先,我要检查数组是否为空:

$ketvirtiRezai = rezultataiKeturi($q);
$tretiRezai = rezultataiTrys($q);
$ketvirtiEmpty = false;
$tretiEmpty = false;
$sphinxEmpty = false;
if (empty($ketvirtiRezai[0])) {
    $ketvirtiEmpty = true;
}
if (empty($tretiRezai[0])) {
    $tretiEmpty = true;
}
else {
    $tretiRezai = array_slice($tretiRezai, 0, 5);
}
if (isset($sphinxorezai) && !empty($sphinxorezai)) {
    $sphinxorezaiclean = array_slice($sphinxorezai, 0, 5);
}
else
{
    $sphinxEmpty = true;
}

,如果elseif循环循环,我可以通过在每个数组中检查true或false并相应地设置array_zip_merge功能来做得很长。

是否有更好的方法将/删除数组添加到array_zip_merge函数。例如,如果$ ketvirtirezai是空的,则仅如果所有数组为空,则功能应包括$visirezai = array_zip_merge($tretiRezai, $sphinxorezaiclean);,则应将$ VisireZai设置为空,并且函数根本不运行(我猜这很容易(。如果不是两个空数,则应将$ Visirezai设置为一个没有空的阵列。

我在PHP中很新,很抱歉我的凌乱代码。

我认为您只需要使用PHP函数is_array,对吗?在您的合并功能中:

function array_zip_merge() {
  $output = array();
  // The loop incrementer takes each array out of the loop as it gets emptied by array_shift().
  for ($args = func_get_args(); count($args); $args = array_filter($args)) {
    // &$arg allows array_shift() to change the original.
    foreach ($args as $key=>&$arg) {
      // check if the argument is actually an array
      if (is_array($arg)) {
        $output[] = array_shift($arg);
      } else {
        unset($args[$key]);
      }
    }
  }
  return $output;
}

最新更新