Monday, January 31, 2011

Grouping an array based on value of the array

this example Groups the array based on color

function groupbyfirst($array)
{

foreach ($array as $row)

{

$firstkeys = array_keys($row);

$firstkey = $firstkeys[0];

$firstkey = strtolower($row[$firstkey]);

$tol = $firstkey;

$newarray[$tol][] = $row;

}

return $newarray;

}



$array =

Array(

0 => Array('color' => 'red','name' => 'apple', 'quantity' => '3'),

1 => Array('color' => 'green','name' => 'pear', 'quantity' => '2'),

2 => Array('color' => 'yellow','name' => 'corn', 'quantity' => '3'),

3 => Array('color' => 'blue','name' => 'grape', 'quantity' => '4'),

4 => Array('color' => 'yellow','name' => 'banana', 'quantity' => '13'),

5 => Array('color' => 'yellow','name' => 'banana', 'quantity' => '15'),

);



$output = groupbyfirst($array);

echo "
";

print_r($output);

echo "
";

No comments:

Post a Comment