How to map arrays?
am 16.10.2007 15:41:53 von kingskippusHi all, I'm using php version 5.2.3. The exact phpinfo page is here:
http://paragonmaps.com/phpinfo.php
I have an array of associative arrays that I would like to break apart
into separate arrays. For example, the top-level array might look
something like this:
// ------------------------------------------------------------ -------
$arr = array(
array("id" => 1, "name" = "foo"),
array("id" => 2, "name" = "bar"),
array("id" => 3, "name" = "monkey"),
array("id" => 4, "name" = "butter")
);
// ------------------------------------------------------------ -------
What I need is two separate arrays that look like this:
// ------------------------------------------------------------ -------
$arr_id = array(1, 2, 3, 4);
$arr_name = array("foo", "bar", "monkey", "butter");
// ------------------------------------------------------------ -------
In perl, this would be a relatively simple task:
# ------------------------------------------------------------ --------
$arr_id = map { $_->{id} } @arr;
$arr_name = map { $_->{name} } @arr;
# ------------------------------------------------------------ --------
I figured out that I can do something like this in php, and it works:
// ------------------------------------------------------------ -------
function map_id($arr_element) {
return $arr_element['id'];
}
function map_name($arr_element) {
return $arr_element['name'];
}
$arr_id = array_map("map_id", $arr);
$arr_name = array_map("map_name", $arr);
// ------------------------------------------------------------ -------
However, I've just got to believe that there is a simpler built-in way
to accomplish this task without manually iterating over all of the
elements of the array via a for or while loop, and without having to
create separate functions for each and every field I want to extract
from the array.
Any suggestions for what would be the easiest way to do this would be
appreciated!
-KS