Here's a function I needed to collapse an array, in my case from a database query. It takes an array that contains key-value pairs and returns an array where they are actually the key and value.
<?php
function array_collapse($arr, $x, $y) {
$carr = array();
while ($el = current($arr)) {
$carr[ $el[$x] ] = $el[$y];
next($arr);
}
return $carr;
}
?>
Example usage (pseudo-database code):
<?php
$query = db_query('SELECT name, value FROM properties');
$result = db_returnAll($query);
/* This will return an array like so:
[
['name' -> 'color', 'value' -> 'blue'],
['name' -> 'style', 'value' -> 'wide-format'],
['name' -> 'weight', 'value' -> 3.6],
['name' -> 'name', 'value' -> 'Waerdthing']
]
*/
$propArr = array_collapse($result, 'name', 'value');
/* Now this array looks like:
[
['color' -> 'blue'],
['style' -> 'wide-format'],
['weight' -> 3.6],
['name' -> 'Waerdthing'],
*/
?>
I found this handy for using with json_encode and am using it for my project http://squidby.com