2012-07-19 20 views
6

Sto provando a contare il numero di volte in cui un determinato valore appare nel mio array multidimensionale in base a una condizione. Ecco un esempio di array;Contare valori specifici nell'array multidimensionale

$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" 
          ) 
      ); 

Se voglio visualizzare tutti i frutti di colore verde, che posso fare quanto segue (fatemi sapere se questo è il modo migliore di farlo);

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

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

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

    } 

} 

In uscita;

Apple 
Grape 

che è grande e posso vedere loro sono 2 valori lì, ma come posso realmente ottenere PHP per contare il numero di frutta dove il colore è verde e metterlo in una variabile per me di utilizzare più in basso il script per lavorare fuori? Per esempio. Voglio fare qualcosa di simile;

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

Ho preso uno sguardo al conteggio(); ma non vedo alcun modo per aggiungere una clausola 'WHERE/condizionale' (a la SQL).

Qualsiasi aiuto sarebbe molto apprezzato.

+0

Invece di ripetere il nome, eseguire il conteggio. 0 + 1 + 1 + 1 + 1 .... – hakre

risposta

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 secondo più veloce di me ;-) +1 – DaveRandom

+0

@DaveRandomL Sì anche +1 anche a te :) Sembra che OP abbia visto solo la tua risposta: P – Blaster

+0

Grazie mille a entrambi. – user1221488

4

Tutto ciò che serve è un contatore in più:

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

Ora mi sento un pazzo, grazie mille amico, accetterò la soluzione in 9 minuti quando me lo consente. – user1221488

8

PHP non ha il supporto per un SQL where genere di cose, soprattutto non con un array di array. Ma si può fare il conteggio proprio mentre si scorrere i dati:

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

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

L'alternativa è quello di scrivere un bel po 'po' di funzione di supporto:

/** 
* 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; 
} 

È quindi possibile ottenere tutti i colori:

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

e poi contare valori:

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

Questo tipo di funzione di supporto è spesso utile per gli array multidimensionali. È anche suggested as a new PHP function for PHP 5.5.

+0

+1 Nizza uno ..... – Baba

Problemi correlati