in_array()期望参数2是数组,给定整数

时间:2017-06-12 18:17:12

标签: php arrays

我想创建每个事件的第一个日期的概述。所以事件标题必须是唯一的。我的想法是创建一个辅助函数,我循环查询结果并检查每个项目的标题。为了确保每个标题只传递一次,我想将标题推送到一个数组($ 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;
}

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

我需要改变什么?

3 个答案:

答案 0 :(得分:4)

添加@Lawrence Cherone和@Ravinder Reddy的答案,而不是使用import React, { Component } from 'react'; class Grid extends Component { constructor(props){ super(props) } componentDidMount () { /* do something */ } render () { return <h1>Hello</h1> } } ,您可以使用本机数组语法推送到数组:

array_push

答案 1 :(得分:2)

它的发生是因为在你的循环中你赋值$checklist的值为array_push(),这将是数组中新的元素数。

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

答案 2 :(得分: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);
            }