PHP中如何检查值是否存在于两个或多个数组中
检查值是否存在于多个数组(结合Laravel集合场景)
看起来你是在Laravel项目里,已经通过Eloquent拿到了分页的Question集合,现在需要实现检查某个值是否存在于多个数组中的功能。我结合你的场景给你分情况说明:
1. 检查值是否在任意一个目标数组中
假设你需要从分页的Question集合里提取两个数组(比如id数组和question_type_id数组),然后判断某个值是否在其中至少一个数组里:
// 从分页集合中提取需要的字段数组 $questionIds = $questions->pluck('id')->toArray(); $questionTypeIds = $questions->pluck('question_type_id')->toArray(); // 你要检查的目标值 $targetValue = 5; // 原生PHP写法 if (in_array($targetValue, $questionIds) || in_array($targetValue, $questionTypeIds)) { // 目标值存在于至少一个数组中,执行你的业务逻辑 dd("值存在!"); } // 更优雅的Laravel集合写法 $hasTarget = collect($questionIds)->contains($targetValue) || collect($questionTypeIds)->contains($targetValue); if ($hasTarget) { // 处理逻辑 }
2. 检查值是否同时存在于所有目标数组中
如果需要确保值在多个数组里都存在:
// 同样先提取数组 $questionIds = $questions->pluck('id')->toArray(); $questionTypeIds = $questions->pluck('question_type_id')->toArray(); $targetValue = 3; // 原生PHP写法 if (in_array($targetValue, $questionIds) && in_array($targetValue, $questionTypeIds)) { // 值同时存在于两个数组中 } // Laravel集合写法 $existsInAll = collect($questionIds)->contains($targetValue) && collect($questionTypeIds)->contains($targetValue); if ($existsInAll) { // 你的业务处理 }
3. 直接在集合层面检查(无需转数组)
如果你不需要单独的数组,而是想直接判断集合中是否存在符合条件的模型(比如某个模型的id或question_type_id等于目标值),可以用集合的contains闭包写法:
$targetValue = 5; // 检查当前分页页中是否有模型的id或question_type_id等于目标值 $hasMatch = $questions->items()->contains(function ($question) use ($targetValue) { return $question->id === $targetValue || $question->question_type_id === $targetValue; }); if ($hasMatch) { // 存在匹配的模型,执行逻辑 }
注意:分页集合 vs 全量集合
你的$questions是LengthAwarePaginator,默认只包含当前页的20条数据。如果需要检查所有符合条件的Question(不是当前页),需要先获取全量集合:
$allQuestions = Question::select('text','question_image','question_type_id','id') ->whereIn('id', $question_ids) ->where('deleted', 0) ->orderBy('created_at','ASC') ->get(); // 之后用$allQuestions来提取数组或检查即可 $questionIds = $allQuestions->pluck('id')->toArray();
内容的提问来源于stack exchange,提问作者Lila
相关产品推荐
相关产品推荐

