You are here: How to map arrays? « PHP Programming Language « IT news, forums, messages
How to map arrays?

Posted by TonyV on 10/16/07 13:41

Hi 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

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация