2012-07-19 47 views
6

我在計算基於條件的多維數組中出現的特定值的次數。這是一個示例數組;在多維數組中計算特定值

$fruit = array (
       "oranges" => array(
            "name" => "Orange", 
            "color" => "orange", 
            "taste" => "sweet", 
            "healthy" => "yes" 
          ), 
       "apples" => array(
            "name" => "Apple", 
            "color" => "green", 
            "taste" => "sweet", 
            "healthy" => "yes" 
          ), 
       "bananas" => array(
            "name" => "Banana", 
            "color" => "yellow", 
            "taste" => "sweet", 
            "healthy" => "yes" 
          ), 
       "grapes" => array(
            "name" => "Grape", 
            "color" => "green", 
            "taste" => "sweet", 
            "healthy" => "yes" 
          ) 
      ); 

如果我要顯示所有綠色的水果,我可以做以下(讓我知道這是做的最好的方式);

for ($row = 0; $row < 3; $row++) { 

    if($fruit[$row]["color"]=="green") { 

     echo $fruit[$row]["name"] . '<br />'; 

    } 

} 

這會輸出;

Apple 
Grape 

這是偉大的,我可以看到他們是2倍的值,但我怎麼能真正得到PHP來算水果,其中的顏色是綠色的數量,並把它放在一個變量再作使用下來腳本工作的東西了嗎?例如。我想做一些事情;

if($number_of_green_fruit > 1) { echo "You have more than 1 piece of green fruit"; } 

我看過count();但我沒有看到任何添加'WHERE /條件'子句(一個SQL)的方法。

任何幫助將非常感激。

+0

而不是回聲的名字,做數。 0 + 1 + 1 + 1 + 1 .... – hakre 2012-07-19 10:08:02

回答

8
$number_of_green_fruit = 0; 
for ($row = 0; $row < 3; $row++) { 
    if($fruit[$row]["color"]=="green") { 
     $number_of_green_fruit++; 
     echo $fruit[$row]["name"] . '<br />'; 
    } 
} 
+0

比我快1秒;-) +1 – DaveRandom 2012-07-19 10:07:17

+0

@DaveRandomL Yep +1給你太:)似乎OP已經看到只有你的答案,但:P – Blaster 2012-07-19 10:07:57

+0

非常感謝你們倆。 – user1221488 2012-07-19 10:12:54

4

所有你需要的是一個額外的計數器:

for ($row = $number_of_green_fruit = 0; $row < 3; $row++) { 
    if($fruit[$row]["color"]=="green") { 
     echo $fruit[$row]["name"] . '<br />'; 
     $number_of_green_fruit++; 
    } 
} 

if($number_of_green_fruit > 1) { 
    echo "You have more than 1 piece of green fruit"; 
} 
+0

我現在覺得自己很笨,非常感謝,我會在9分鐘內接受解決方案。 – user1221488 2012-07-19 10:07:55

8

PHP有一個SQL where之類的事情的支持,特別是沒有一個數組的數組。但是,當你遍歷數據,你可以做的統計你自己:

$count = array(); 
foreach($fruit as $one) 
{ 
    @$count[$one['color']]++; 
} 

printf("You have %d green fruit(s).\n", $count['green']); 

另一種方法是你自己寫的一些小幫手功能:

/** 
* array_column 
* 
* @param array $array rows - multidimensional 
* @param int|string $key column 
* @return array; 
*/ 
function array_column($array, $key) { 
    $column = array(); 
    foreach($array as $origKey => $value) { 
     if (isset($value[$key])) { 
      $column[$origKey] = $value[$key]; 
     }    
    } 
    return $column; 
} 

然後,您可以得到所有的顏色:

$colors = array_column($fruit, 'color'); 

再算上值:

$count = array_count_values($colors); 
printf("You have %d green fruit(s).\n", $count['green']); 

這種輔助函數通常對多維數組很有用。這也是suggested as a new PHP function for PHP 5.5

+0

+1不錯的一個..... – Baba 2012-10-06 16:14:02