note 88428 added to function.array-keys
| From: | ferrerna at gmail dot com | Date: | Fri, 23 Jan 2009 17:14:15 +0000 |
| Subject: | note 88428 added to function.array-keys | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-149704@lists.php.net to get a copy of this message | ||
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
----
Server IP: 64.71.164.2
Probable Submitter: 69.214.9.69
----
Manual Page -- http://www.php.net/manual/en/function.array-keys.php
Edit -- https://master.php.net/note/edit/88428
Del: integrated -- https://master.php.net/note/delete/88428/integrated
Del: useless -- https://master.php.net/note/delete/88428/useless
Del: bad code -- https://master.php.net/note/delete/88428/bad+code
Del: spam -- https://master.php.net/note/delete/88428/spam
Del: non-english -- https://master.php.net/note/delete/88428/non-english
Del: in docs -- https://master.php.net/note/delete/88428/in+docs
Del: other reasons-- https://master.php.net/note/delete/88428
Reject -- https://master.php.net/note/reject/88428
Search -- https://master.php.net/manage/user-notes.php