循环数组中的项,并将它们分布在php中的一行中


loop over items in an array and spread them in one line in php

我知道这有点愚蠢,但我追求的是

// an array of some unknown items from the database
$array = ['item1','item2','item3'];
// i think it should be done with For loop but not sure how, so anyhow
// the loop should repeat (name contains '$item' and) for each item of the $array and put them in a query like below
foreach ($array as $item) {
    $query = [
        'q' => "name contains '$item1' and name contains '$item2' and name contains '$etc...'"
    ];
}

目前正在做的是一个接一个地进行查询,这会导致开销,而且对于大数组来说,这需要很长时间,所以我考虑将整个查询组合在一个查询中,这将大大减少时间。

// an array of some unknown items from the database
$array = ['item1','item2','item3'];
$q = array();
foreach ($array as $item) {
    $q[]  = "name contains '$item'";
}
$query['q'] = implode(' and ', $q);

像这样的东西应该可以做到:

$array = ['item1','item2','item3'];
// init $query as array
$query = [];
// init $query 'q' index as empty string
$query['q'] = '';
// then loop the array of items, and concat what you need    
foreach ($array as $item)
{
    $query['q'] .= " name contains '$item' and";
}
// remove whitespaces from start and end of the string
$query['q'] = trim($query['q']);
// remove the ' and' from the end of the string (0 = start of string, -4 = 4 before the end of the string)
$query['q'] = substr($query['q'], 0, -4);

这将返回:name contains 'item1' and name contains 'item2' and name contains 'item3'

因为这是一个简单的例子,你应该用empty($array)测试这个例子,数组至少包含一个项,子字符串将返回false(或null,我不确定)

不需要foreach

$query['q'] = "name contains " . implode(" and name contains ", $array);

但是您需要确保数组中包含一些内容。:-)