如何检查给定数组中是否存在特定值?

How to check if a specific value exists in a given array?

这是数组:

<input name="gallery[0][file]" value="file"> // could be empty or zip or image file 
<input name="gallery[0][main]" value="false">  // one of main must be true

<input name="gallery[1][file]" value="file"> // could be empty or zip or image file
<input name="gallery[1][main]" value="true"> // one of main must be true

<input name="gallery[2][file]" value="file"> // could be empty or zip or image file
<input name="gallery[2][main]" value="false"> // one of main must be true

我想确保列表中的“主要”输入之一是正确的。

我该怎么做?这是我目前的规则

return [
    'gallery' => 'required|array',
    'gallery.*.file' => 'required|max:30000',
    'gallery.*.main' => 'required|in:true,false',
];

一个选项是预处理数据并添加一个带有检查结果的虚拟字段:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreGallery extends FormRequest
{
    protected function prepareForValidation()
    {
        // pull out gallery.*.main values
        $mains = array_column($this->gallery, "main");
        // filter out values that are not "true"
        $result = array_filter($mains, fn ($v) => $v === "true");
        // add a field to the request with the results
        $this->merge(["main_trues" => count($result)]);
    }
    public function rules()
    {
        return [
            'gallery' => 'required|array',
            // your comment says this could be empty, so don't mark it required
            'gallery.*.file' => 'sometimes|file|max:30000',
            // boolean checks for 0,1,true,false
            'gallery.*.main' => 'required|boolean',
            // here's our fake field, make sure it's at least 1
            'main_trues' => 'required|integer|gte:1',
        ];
    }
    public function messages()
    {
        return [
            'main_trues' => 'At least one main must be true',
        ];
    }
}

不太可靠,但在客户端使用 JavaScript 和隐藏字段可能更容易。

可以尝试关闭自定义验证

public function rules()
{
    return [
        'gallery' => ['required', 'array'],
        'gallery.*.file' => ['required', 'max:30000'],
        'gallery.*.main' => [
            'required',
            function($attribute, $value, $fail) {
                $count = 0;
                foreach(request()['gallery'] as $item) {
                    if(in_array($item['main'], [1, '1', true, 'true'], true)) {
                        $count++;
                    }
                }
                if($count === 0) {
                    $fail('At least one main must be true');
                }
            }
    ];
}