【问题标题】:How to make a search in array with where collection laravel如何使用 where 集合 laravel 在数组中进行搜索
【发布时间】:2021-03-30 23:26:18
【问题描述】:

我有这样的数据数组:

[
   {
      fruit: "Apple",
      price: "10",
   },
   {
      fruit: "Orange",
      price: "12",
   },
   {
      fruit: "Manggo",
      price: "14",
   },
   {
      fruit: "Grape",
      price: "16",
   },
  {
      fruit: "Apple",
      price: "13",
   },
]

如何从我的数据中使用搜索方法来查找具有输入类型的数据?在此之前,我想展示我所做的,这是我的代码:

$search = "Apple"; // let's just say the value of this variable comes from the input type

$myData = [
   [fruit: "Apple", price: "10"],
   [fruit: "Orange", price: "12"],
   [fruit: "Manggo", price: "14"],
   [fruit: "Grape", price: "16"],
   [fruit: "Apple", price: "13"],
];

$getSearch = collect($myData)->where('fruit', $search)->all();

var_dump($getSearch);

对于输出,我没有从我的结果中得到任何东西,就像这样:

array(0) {

}
array(0) {

}
array(0) {

}
array(0) {

}

为了期待,我的结果变成了这样:

[
   {
      fruit: "Apple",
      price: "10",
   },
   {
      fruit: "Apple",
      price: "13",
   },
]

【问题讨论】:

    标签: arrays laravel search collections


    【解决方案1】:

    您的 $myData 不是有效的 php 数组

    参考链接https://www.php.net/manual/en/language.types.array.php

    这是解决办法

    $myData  = [
        [
            'fruit' => 'Apple',
            'price' => '10',
        ],
        [
            'fruit' => 'Orange',
            'price' => '12',
        ],
        [
            'fruit' => 'Manggo',
            'price' => '14',
        ],
        [
            'fruit' => 'Grape',
            'price' => '16',
        ],
        [
            'fruit' => 'Apple',
            'price' => '13',
        ]
    ];
    
    $search = "Apple"; 
    $getSearch = collect($myData)->where('fruit', $search)->all();
    var_dump($getSearch);
    

    这段代码结果是

    {
        "0": {
            "fruit": "Apple",
            "price": "10"
        },
        "4": {
            "fruit": "Apple",
            "price": "13"
        }
    }
    

    【讨论】:

    • 之前谢谢你的回答,我已经试过你告诉先生的,但结果仍然是0
    • @LuckALip laravelplayground.com/# 在这里测试
    • 对不起先生,我的输入类型有误,我的问题已经解决了!谢谢
    猜你喜欢
    • 2021-08-15
    • 2020-12-12
    • 2016-07-29
    • 2020-10-29
    • 2019-05-21
    • 2020-02-07
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多