2012-09-21 64 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

相關問題