我如何基于数组的长度循环

时间:2019-08-20 03:45:03

标签: php mysql eloquent

我的输入是'[ Company_A,Company_B,Company_C]',它是一个字符串,我已经在使用了

$array = explode(',', (trim($filters->input('provider'), '[]')));

进行转换。

我的过滤器

public $array;
public $i, $j;

public static function apply(Request $filters, $size, $bonus)
{
if ($filters->has('provider') && trim($filters->input('provider')) != "") {
        $bonus->whereHas('bonusCompany', function ($query) use ($filters) {
            $array = explode(',', (trim($filters->input('provider'), '[]')));
            $j = count($array);
            echo count($array);
            for ($i = 0; $i < $j; $i++) {
                $query->where('providers', 'like', ['%' . $array[$i] . '%']);
                echo $array[$i];
                echo $filters->input('provider');
            }
        });

我正在尝试获取providers$array[0]$array[1]等于$array[2]的数据。我的Company_A,Company_B,Company_C字段是json格式,因此我使用providerslike进行匹配。在这样做时,我使用了for循环来执行此操作,但是以某种方式我无法获取任何数据。

输出

enter image description here

如您所见,我尝试打印%,其值为count($array)。 并且3 = echo $array[$i] 与我的输入匹配。

我尝试将Company_A,Company_B,Company_C的这一行更改为$query->where('providers', 'like', ['%' . $array[$i] . '%']);

,我得到$query->where('providers', 'like', ['%' . $array[0] . '%']); = provider的所有数据,这是我的第一个输入(因此,我假设我的代码是有效的。 但是为什么Company_A无法正常工作?

我已经打印出我的$array[$i] 这就是我得到的

echo $query->toSql();

正确的查询应该是

select * from `bonus_Company` where `bonuses`.`id` = `bonus_Company`.`fk_bonus_id` and `providers` = ?
select * from `bonus_Company` where `bonuses`.`id` = `bonus_Company`.`fk_bonus_id` and `providers` = ? and `providers` = ?
select * from `bonus_Company` where `bonuses`.`id` = `bonus_Company`.`fk_bonus_id` and `providers` = ? and `providers` = ? and `providers` = ?

3 个答案:

答案 0 :(得分:2)

here is sql database table

$string = "company_A, company_B"; //string of company names you want to search
$array = explode( ",", $string); //convert string to array
$i = 1;    
$qry = "SELECT * from `company` ";
foreach($array as $companyName) {            
        if($i <= 1){
            $qry .= " WHERE `providers` LIKE '%".trim($companyName)."%' ";
        } else {
            $qry .= " OR `providers` LIKE '%".trim($companyName)."%' ";
        }            
        $i += 1;            
}    
$result = mysqli_query($connection, $qry); 
$companies = mysqli_fetch_assoc($result);     
foreach ($companies as $companyName){
    echo $companyName;
}

Here is result in second image

答案 1 :(得分:1)

您可以通过两种方式进行操作。

1)

$array = explode(',', (trim($filters->input('provider'), '[]')));
foreach ($array as $a) {
    $query->where('providers', 'like', ['%' . $a . '%']);
    echo $a;
    echo $filters->input('provider');
}

答案 2 :(得分:-1)

调试失败的SQL查询的最佳方法是查看查询日志:

https://laravel.com/docs/5.0/database#query-logging

DB::connection()->enableQueryLog()

// code you want to debug

$queries = DB::getQueryLog();
print_r($queries);