简体   繁体   English

如何从基于数组的MySQL数据库获取数据

[英]How to get data from mysql database based on array

So I have table called paint with data like below 所以我有一个叫做paint的表,数据如下

id            name               allow_on
------------------------------------------
1             Avian           Wall|Roof|Wood
2             Avitex          Wall|Roof|Iron
3             Nippon          Floor|Iron
4             Some            Plastic|Cloth|other

And how to get field based on allow_on column, like "I want paint which can be used on wall" , so far my code look like this 以及如何基于allow_on列获取字段,例如“我想要可以在墙上使用的油漆”,到目前为止,我的代码看起来像这样

$paints = Paint::get();
foreach($paints as $paint)
{
     $exp = explode("|", $paint->allow_on);
     foreach($exp as $pnt)
     {
         if(in_array($request->paint_name,$pnt))
         {
            var_dump($pnt)
         }
     }
}

I'm using Laravel 5.4 but i can't make it working, any solution? 我正在使用Laravel 5.4,但是我无法使其正常运行,有解决方案吗? Thanks in advance. 提前致谢。

You are confusing the use of the needle and haystack when using in_array() 使用in_array()时,您会混淆使用needle和haystack

The haystack should be an array ie the $exp array in your example 干草堆应该是一个数组,即示例中的$exp数组

$paints = Paint::get();
foreach($paints as $paint)
{
     $exp = explode("|", $paint->allow_on);

    if(in_array($request->paint_name,$exp)) {
            // yes paint_name is in the array
     }
}
$want    = 'Wall';
$allowed = Paint::where('allow_on', 'like', '%'.$want.'%')->get();

foreach ($allowed as $allowedPaint) {
    echo $allowedPaint->name;
}

The above will get you all paints which can be used on wall. 以上将为您提供所有可以在墙上使用的油漆。 If you need to retrieve only the paint names, you can use: 如果只需要检索油漆名称,则可以使用:

$allowed = Paint::where('allow_on', 'like', '%'.$want.'%')->pluck('name');
var_dump($allowed);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM