7

可能重复:
搜索包含字符串的 PHP 数组元素

我创建了一个 mysql 查询,该查询包含多个产品,所有产品都包含以下信息:

产品编号 产品名称 产品价格和产品类别

在页面的下方,我用一个 foreach 和一些“ifs”遍历了这些内容,因此它只显示名称在一个 div 中包含“x”的那些产品,并在另一个 div 中显示名称包含“y”的那些产品.

在进行循环之前,我正在努力计算每个 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>

在我实际执行循环之前,我想知道其中有多少会出现在这里。

4

2 回答 2

11

好吧,没有看到代码,所以一般来说,如果你无论如何都要拆分它们,你还不如预先做呢?

<?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 中更快”的注释,因为如果您想过滤值,这是更明智的方法。

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

于 2012-09-21T11:37:49.600 回答
3

使用数组过滤器: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 查询会更快。

于 2012-09-21T11:38:24.357 回答