[英]in_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).
为了确保每个标题只传递一次,我想将标题推送到一个数组($ 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. 我已经尝试将$ checklist和$ result作为数组转换为foreach循环但没有结果。
What do I need to change? 我需要改变什么?
Adding to @Lawrence Cherone and @Ravinder Reddy's answers, instead of using array_push
, you could use native array syntax to push to the array: 添加@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. 它的发生是因为在你的循环中你使用
array_push()
的值分配$checklist
,这将是数组中新的元素数。
http://php.net/manual/en/function.array-push.php http://php.net/manual/en/function.array-push.php
array_push function will return the count of array after an element is added to array. 在将元素添加到数组后,array_push函数将返回数组的计数。 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.