循环遍历数组中的项目并将它们分散在php

时间:2016-05-07 14:54:27

标签: php arrays

我知道它有点愚蠢,但后面是什么,

// 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...'"
    ];
}

目前正在做的是一个接一个地进行查询,导致开销和大数组需要太长时间,所以我想在一个查询中将整个事情结合起来,这会大大减少时间。

4 个答案:

答案 0 :(得分:2)

 <script type='text/javascript'>
   var s = document.createElement('script');
   s.type = 'text/javascript';
   s.src = 'app/services/authInterceptorService.js?dev=' + GetRandomNumber();
   document.body.appendChild(s);
</script>

答案 1 :(得分:1)

像这样的Somethig可以做到这一点:

$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'

Becare,这是一个简单的例子,你应该用empty($array)来测试数组包含至少一个项目的例子,substr将返回false(或者null,我不确定这个)

答案 2 :(得分:0)

不需要until python data.py "$@" ; do

foreach

但你要确保数组中有一些东西......: - )

答案 3 :(得分:-2)

for($array as $item) {
   $query .= " AND name=$item";// Dont forget "."
}