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

I want to create an overview of the first dates of every event. So the event-title must be unique. My idea was to create a helper-function where I loop over the result of my query and check the title of every item. To make sure every title passes only once, I want to push the title into an array ($checklist). If it does not exist, I add that item to the result-array. If it does, just continue to the next item.

I always get the error:

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

This is my code:

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;
}

I already tried to cast $checklist and $result as array in the foreach loop but without result.

What do I need to change?


array_push function will return the count of array after an element is added to array. so dont assing the output of the function to array.

Replace

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

with

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

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

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

Its happening because within your loop your assigning $checklist with the value of array_push() which will be the new number of elements in the array.

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

链接地址: http://www.djcxy.com/p/59412.html

上一篇: 从Wordpress $ wpdb构建新的自定义数组

下一篇: array()期望参数2是数组,给定的整数