我创建了一个mysql查询,它通过以下信息提取了几个产品:
产品ID 产品名称 产品价格 和 产品类别
在页面的下方,我通过foreach和一些'ifs'循环使用这些,因此它只显示名称中包含'x'的产品,并显示名称中包含'y'的产品在另一个div。
在进行循环之前,我很难计算每个div中会有多少产品。
基本上,我要问的是:
如何计算数组中满足特定条件的所有元素?
添加了显示循环的代码:
<div id="a">
<?php
$i = 1;
foreach ($products AS $product) {
if (strpos($product->name,'X') !== false) {
=$product->name
}
$i++;
} ?>
</div>
<div id="b">
$i = 1;
foreach ($products AS $product) {
if (strpos($product->name,'Y') !== false) {
=$product->name
}
$i++;
} ?>
</div>
我想知道在我实际进行循环之前,其中有多少会在这里。
答案 0 :(得分:6)
嗯,没有看到代码,所以一般来说,如果你打算将它们分开,你还可以预先做到这一点吗?
<?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中更快”,因为如果你想过滤这些值,这是更合理的方法。
编辑:更改了变量的名称以适应示例代码中的变量名称。
答案 1 :(得分: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查询会更快。