note 50389 added to function.array-combine

From: Date: Sat, 26 Feb 2005 18:53:03 +0000
Subject: note 50389 added to function.array-combine
Groups: php.notes 
Request: Send a blank email to php-notes+get-85586@lists.php.net to get a copy of this message
Use that code to group an array by its first element. <? function groupbyfirst($array) { foreach ($array as $row) { $firstkey = array_keys($row); $firstkey = $firstkey[0]; $key = $row[$firstkey]; unset($row[$firstkey]); $newarray[$key][] = $row; } return $newarray; } ?> Example: <? $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'), ); $output = groupbyfirst($array); print_r($output); ?> will return: Array ( [red] => Array ( [0] => Array ( [name] => apple [quantity] => 3 ) ) [green] => Array ( [0] => Array ( [name] => pear [quantity] => 2 ) ) [yellow] => Array ( [0] => Array ( [name] => corn [quantity] => 3 ), [1] => Array ( [name] => banana [quantity] => 13 ) ) [blue] => Array ( [0] => Array ( [name] => grape [quantity] => 4 )) ) Or you can use mysql recordset: <? while ($row=mysql_fetch_array($result,MYSQL_ASSOC)) { $firstkey = array_keys($row); $firstkey = $firstkey[0]; $key = $row[$firstkey]; unset($row[$firstkey]); $newarray[$key][] = $row; } ?> ---- Manual Page -- http://www.php.net/manual/en/function.array-combine.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+50389 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+50389&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+50389&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+50389&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+50389&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+50389&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+50389&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#85586) next »