I constantly find that I am executing queries in databases and getting multidimensional arrays representing rows back. Unfortunately, the first level index is numerical, which is not very informative. I often have tables with identical rows in the table and want to turn the resulting multidimensional array into something that is associatively indexed by this identity column.
Inelegant, self-contained user function to accomplish what I want:
function identity_associate($data, $identity_column='identity'){
$res = array();
foreach($data as $single_row){
$loop_identity = $single_row[$identity_column];
$res[$loop_identity] = $single_row;
}
return $res;
}
Obviously, I could use the foreach loop every time I want, or use this function to do this when I pass data to it every time, but if there is a built-in way to do this is trivial with, I would prefer to use this to fix it. I tried to find something suitable in php docs for sorting and arrays, but could not find anything exact, and google did not help either. Does anyone know something php native or otherwise easier?
i.e. I want to convert the data that I receive when I query the database ...
array(
array(
'user_id'=>45,
'identity'=>'bob',
'name'=>'Bob'
),
array(
'user_id'=>51,
'identity'=>'tchalvak',
'name'=>'TchalVak'
)
);
into something more comfortable
array(
'bob'=>array(
'user_id'=>45,
'identity'=>'bob',
'name'=>'Bob'
),
'tchalvak'=>array(
'user_id'=>51,
'identity'=>'tchalvak',
'name'=>'TchalVak'
)
);
as optimized as possible, as this is what I will use everywhere all the time.
Edit:
I want to indicate that I get data in this format from the database by calling the built-in function in the PDO and returning the equivalent of the first array:
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
eg. calling sql below:
$data = query('select name, user_id, identity from users order by identity');
... will get the first array at the beginning of the question.