gabordemooij/redbean — pull request #101 by rainphp (2011-11-05 01:11:40+00:00)
Title: getAll results key indexed

I added 2 new parameters to getAll, both optional, $key and $value.
With these new parameters you can get the result of a query as an associative array.
Both parameters have to be selected in the query as fields.
If you set $key, the result will be an associative array with $key as key and the rows as array,
if you set both $key and $value, the result will be an associative array with the couples (key => value) for each rows selected by the query.

Definition:
R::getAll( $query, $values = array(), $key = null, $value = null);

Examples:
// return the array of all users in an associative array where the key is "id" and the value is the selected row
R::getAll( "SELECT * FROM user", array (), "id" );

output:
array( 1 => array( "id"=>1, "name"=> "Gabor", "sex" => "m", "state" => "NY" ),
5 => array( "id"=>5, "name"=> "Rain", "sex" => "m", "state" => "NY" ),
7 => array( "id"=>6, "name"=> "Sheska", "sex" => "f", "state" => "NY" ) )

// return the array of all users in an associative array with selected key "id" and value is "name"
R::getAll( "SELECT * FROM user", array (), "id", "name" );

output:
array( 1 => "Gabor",
5 => "Rain",
7 => "Sheska" );

This feature is very useful when you need to retrive any kind of list that you need to apply to any html list, for example a combo-box or options list. As a practical example you may want to get an array (country_code => country_name) that might be used in a field "Select country". Also useful to get an array with contents ordered by id, in this way you can access any contents of the array directly with the id.

Best,
Rain.