note 80009 added to ref.array
| From: | phpatdomainyerethincountrynl at osu1 dot php dot net | Date: | Mon, 24 Dec 2007 12:24:42 +0000 |
| Subject: | note 80009 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-133969@lists.php.net to get a copy of this message | ||
I was looking for a array transpose but surprisingly it's not in PHP.
Here's my humble version:
<?php
function array_transpose($array, $selectKey = false) {
if (!is_array($array)) return false;
$return = array();
foreach($array as $key => $value) {
if (!is_array($value)) return $array;
if ($selectKey) {
if (isset($value[$selectKey])) $return[] = $value[$selectKey];
} else {
foreach ($value as $key2 => $value2) {
$return[$key2][$key] = $value2;
}
}
}
return $return;
}
?>
As you can see, it does a bit more. You can submit a Key name, which should be selected from the
transposed array, if you only want that specific key.
Examples:
<?php
$people = array(
array('id' => 1, 'name' => 'john',
'occupation' => 'unemployed'),
array('id' => 5, 'name' => 'pete',
'occupation' => 'dentist'),
array('id' => 19, 'name' => 'hank',
'occupation' => 'software developer')
);
print_r(array_transpose($people));
print_r(array_transpose($people, 'name'));
?>
Will output:
Array(
[id] => Array(
[0] => 1
[1] => 5
[2] => 19
)
[name] => Array (
[0] => john
[1] => pete
[2] => hank
)
[occupation] => Array (
[0] => unemployed
[1] => dentist
[2] => software developer
)
)
Array (
[0] => john
[1] => pete
[2] => hank
)
I use it all the time, especially for structured array data such as this.
----
Server IP: 64.71.164.2
Probable Submitter: 80.126.149.92
----
Manual Page -- http://www.php.net/manual/en/ref.array.php
Edit -- https://master.php.net/note/edit/80009
Del: integrated -- https://master.php.net/note/delete/80009/integrated
Del: useless -- https://master.php.net/note/delete/80009/useless
Del: bad code -- https://master.php.net/note/delete/80009/bad+code
Del: spam -- https://master.php.net/note/delete/80009/spam
Del: non-english -- https://master.php.net/note/delete/80009/non-english
Del: in docs -- https://master.php.net/note/delete/80009/in+docs
Del: other reasons-- https://master.php.net/note/delete/80009
Reject -- https://master.php.net/note/reject/80009
Search -- https://master.php.net/manage/user-notes.php