Note Submitter: php atdomain yereth incountry nl
----
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.
lmpx.com only provides a reader for public news (NNTP) servers. It is not
affiliated with the servers or forums shown here and is not responsible for
the content of articles, which is written by their respective authors.