【问题标题】:in_array() expects parameter 2 to be array, integer givenin_array() 期望参数 2 是数组,给定整数
【发布时间】:2017-11-14 07:49:48
【问题描述】:

我想创建每个事件的第一个日期的概述。所以事件标题必须是唯一的。我的想法是创建一个辅助函数,在其中循环查询结果并检查每个项目的标题。为了确保每个标题只通过一次,我想将标题推入一个数组($checklist)。如果它不存在,我将该项目添加到结果数组中。如果是,请继续下一项。

我总是得到错误:

in_array() expects parameter 2 to be array, integer given

这是我的代码:

function showFirstEvenst($collection) {
    $checklist = array();
    $result = array();

    foreach ($collection as $item) {
        $title = strtolower($item['events']['title']);

        if (!in_array($title, $checklist)) {
            $checklist = array_push($checklist, $title);
            $result = array_push($result, $item);
        }
    }

    return $result;
}

我已经尝试在 foreach 循环中将 $checklist 和 $result 转换为数组,但没有结果。

我需要改变什么?

【问题讨论】:

标签: php arrays


【解决方案1】:

添加到@Lawrence Cherone 和@Ravinder Reddy 的答案,而不是使用array_push,您可以使用本机数组语法推送到数组:

if (!in_array($title, $checklist)) {
    $checklist[] = $title;
    $result[] = $item;
}

【讨论】:

  • 事实上,array_push 文档建议您在仅附加一项时这样做。
【解决方案2】:

array_push 函数将在将元素添加到数组后返回数组的计数。所以不要将函数的输出分配给数组。

替换

  if (!in_array($title, $checklist)) {
                $checklist = array_push($checklist, $title);
                $result = array_push($result, $item);
            }

 if (!in_array($title, $checklist)) {
               array_push($checklist, $title);
               array_push($result, $item);
            }

【讨论】:

  • 这确实是问题所在......不是在寻找那个。
【解决方案3】:

之所以发生,是因为在您的循环中,您将 $checklist 分配给了 array_push() 的值,这将是数组中的新元素数。

http://php.net/manual/en/function.array-push.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 2016-03-23
    • 2017-08-26
    • 2018-03-23
    • 2014-06-19
    相关资源
    最近更新 更多