2012-09-21 62 views
4

可能重复:
Search for PHP array element containing stringPHP - 计数的数组的所有元素满足条件的

我创建了一个MySQL查询,通过几种产品拉,全部采用以下信息:

产品编号 产品名称 产品价格 and 产品分类

再往下看,我用foreach和几个'ifs'循环了这些,因此它只显示那些名称在一个div中包含'x'的产品,并显示这些产品的名称在另一个div中包含'y'。

我很努力地计算在做循环之前每个div中会有多少产品。

所以基本上,我要问的是:

你怎么指望在满足一定条件的数组的所有元素?

添加的代码这显示了环:

 <div id="a"> 
     <?php $i = 1; foreach ($products AS $product) { ?> 
      <?php if (strpos($product->name,'X') !== false) { ?> 
      <?=$product->name?> 
      <?php } ?>    
     <?php $i++; } ?> 
     </div> 

     <div id="b"> 
     <?php $i = 1; foreach ($products AS $product) { ?> 
      <?php if (strpos($product->name,'Y') !== false) { ?> 
      <?=$product->name?> 
      <?php } ?>    
     <?php $i++; } ?> 
     </div> 

我想知道有多少,这些都将是在这里,我实际上做循环之前。

+0

显示一些代码... –

+3

这通常在SQL中更快。你可能想看看发射查询计数 – Sammaye

+1

你可以发布你的代码在哪里你奋斗 – Surace

回答

3

那么,没有看到代码,所以一般来说,如果你打算分裂他们,你也可以做前面的事情吗?

<?php 
// getting all the results. 
$products = $db->query('SELECT name FROM foo')->fetchAll(); 

$div1 = array_filter($products, function($product) { 
    // condition which makes a result belong to div1. 
    return substr('X', $product->name) !== false; 
}); 

$div2 = array_filter($products, function($product) { 
    // condition which makes a result belong to div2. 
    return substr('Y', $product->name) !== false; 
}); 

printf("%d elements in div1", count($div1)); 
printf("%d elements in div2", count($div2)); 

// then print the divs. No need for ifs here, because results are already filtered. 
echo '<div id="a">' . PHP_EOL; 
foreach($div1 as $product) { 
    echo $product->name; 
} 
echo '</div>'; 

echo '<div id="b">' . PHP_EOL; 
foreach($div2 as $product) { 
    echo $product->name; 
} 
echo '</div>'; 

话虽这么说:如果你要过滤的值,你应该采取它说“这通常快于SQL是”意见的通知,因为它是更理智的方式。

编辑:更改了变量的名称以适应示例代码中的变量名称。

+0

工作很好!谢谢! –

+0

@DanielKilburn真棒,不用了,谢谢! –

+0

你如何访问array_filter子函数内的外部变量?即不是使用'X'和'Y',而是使用我在外部设置的变量 – Mir

2

使用的阵列滤波器:http://www.php.net/manual/en/function.array-filter.php

array array_filter (array $input [, callable $callback = "" ]) 

在迭代将它们传递给回调函数的输入阵列中的每个值。如果回调函数返回true,则来自输入的当前值将返回到结果数组中。数组键被保留。

<?php 
function odd($var) 
{ 
    // returns whether the input integer is odd 
    return($var & 1); 
} 

function even($var) 
{ 
    // returns whether the input integer is even 
    return(!($var & 1)); 
} 

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5); 
$array2 = array(6, 7, 8, 9, 10, 11, 12); 

echo "Odd :\n"; 
print_r(array_filter($array1, "odd")); 
echo "Even:\n"; 
print_r(array_filter($array2, "even")); 
?> 

但请注意,虽然这是一个循环,并且您的SQL查询将会更快。

+1

这是从手册中得出的...至少有一个适用于他的场景的答案... – Sammaye

相关问题