Friday, August 21, 2009

use array_map to select 1 column out of rowset of php rows

Given a series of rows of data (perhaps rows in a database, copied into memory), we want to extract only 1 field of data and put it into a comma delimited list. (or array to loop through).


$arr = array();
$arr[] = array('first'=>'jack','last'=>'smith');
$arr[] = array('first'=>'john','last'=>'williams');
$arr[] = array('first'=>'mark','last'=>'jesperson');
$arr[] = array('first'=>'vlad','last'=>'shuttleworth');

$f = array_map(create_function('$a', 'return $a["first"];') , $arr);
echo implode(",", $f);
//outputs:
//jack,john,mark,vlad