How to count the consecutive duplicate values in an array?

It can be done simply manually: $arr = array(1,1,1,2,2,3,3,1,1,2,2,3); $result = array(); $prev_value = array(‘value’ => null, ‘amount’ => null); foreach ($arr as $val) { if ($prev_value[‘value’] != $val) { unset($prev_value); $prev_value = array(‘value’ => $val, ‘amount’ => 0); $result[] =& $prev_value; } $prev_value[‘amount’]++; } var_dump($result);

Group rows in a 2d array and count number of rows in each respective group

Just iterate over the array and use another array for the groups. It should be fast enough and is probably faster than the overhead involved when using sqlite or similar. $groups = array(); foreach ($data as $item) { $key = $item[‘key_to_group’]; if (!isset($groups[$key])) { $groups[$key] = array( ‘items’ => array($item), ‘count’ => 1, ); } … Read more

Display and count qualifying data from a 2d array

PHP has no support for a SQL where sort of thing, especially not with an array of arrays. But you can do the counting your own while you iterate over the data: $count = array(); foreach($fruit as $one) { @$count[$one[‘color’]]++; } printf(“You have %d green fruit(s).\n”, $count[‘green’]); The alternative is to write yourself some little … Read more

Group 2d array’s row data by one column and sum another column within each group to produce a reduced 2d array

Just loop trough the rows, and add up the quantities in a different array indexed by the dd values. $in = array(array()); // your input $out = array(); foreach ($in as $row) { if (!isset($out[$row[‘dd’]])) { $out[$row[‘dd’]] = array( ‘dd’ => $row[‘dd’], ‘quantity’ => 0, ); } $out[$row[‘dd’]][‘quantity’] += $row[‘quantity’]; } $out = array_values($out); // … Read more