array_collect, mapping required fields to a PHP array
December 09, 2008 at 10:30 AM · Posted under Blog · Tagged with array, function, php
After delving around in ruby for a little and finding the magic that is the Array.collect method, I decided to write one for PHP, considering how much I use it in Ruby. Hopefully others will find some use in this function.
<?php
function array_collect($array, $params)
{
$return = array();
if (!is_array($params)) {
$params = array($params);
}
foreach ($array as $record) {
$rec_ret = array();
foreach ($params as $search_term) {
if (array_key_exists($search_term, $record)) {
$rec_ret[$search_term] = $record[$search_term];
}
}
if (count($rec_ret) > 0) {
$return[] = $rec_ret;
}
}
return $return;
}
?>
Basically, what this allows us to do is extract information from an array and have it stored in another array. For example, we may only want a few select fields as a subset of data, we could do this by doing:
$records = array(array('a' => 'y', 'b' => 'z', 'c' => 'e'), array('a' => 'x', 'b' => 'w', 'c' => 'f'));
$subset1 = array_collect($records, 'a'); // $subset1 will be: array(array('a' => 'y'), array('a' => 'x'));
$subset2 = array_collect($records, array('a', 'c')); // $subset2 will be: array(array('a' => 'y', 'c' => 'e'), array('a' => 'x', 'c' => 'f'));
Permalink
Comments
Arnold said @ Apr 15, 2009 @ 08:04 PM
you should check out the
Set::extract()
Set::combine()
in the cake lib ;)
Kirk Bushell said @ Apr 17, 2009 @ 08:37 AM
@arnold - which is great if you're working with Cake, but if you're not - then what do you do? :)
Arnold Almeida said @ May 11, 2009 @ 03:08 PM
import the required cake libs ;)
Craig Morris said @ May 11, 2009 @ 03:10 PM
@kirk - the library is pretty independent from a quick look through it then.... http://thechaw.com/cakephp/source/cake/libs/set.php
RSS feed for comments on this post
Leave a Comment