简体   繁体   中英

How to get data from mysql database based on array

So I have table called paint with data like below

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

$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? Thanks in advance.

You are confusing the use of the needle and haystack when using in_array()

The haystack should be an array ie the $exp array in your example

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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