On 2012-06-26 07:22, Ben Ramsey wrote:

However, in Prototype.js and Underscore.js, pluck seems behave more like
array_map() in PHP:

http://api.prototypejs.org/language/Enumerable/prototype/pluck/
http://documentcloud.github.com/underscore/#pluck

Nevertheless, it would technically have the same effect as the "column"
functionality, since calling that method/property in Javascript simply
returns the value of the property or result of the method call.

Remember that, in JavaScript, "foo.length" is equivalent to "foo['length']". The use case for map that pluck was created to cover is basically the same one here - essentially:

function array_{column|pluck}($array, $key)
{
    return array_map(function($element)use($key)
    {
        return $element[$key];
    }, $array);
};

Or, as it's implemented in Prototype.js (which inlines the map invocation),

function pluck(property) {
    var results = [];
    this.each(function(value) {
        results.push(value[property]);
    });
    return results;
}


I will say I'm not sold on "pluck" since it describes the physical action (a sharp tug) rather than the intended result (you pluck feathers from a chicken but you pluck fruit from a tree). Other alternatives to array_column that have crossed my mind include:

An extra argument to array_values() analogous to the extra argument to array_keys(): I'm worried the analogy isn't close enough to excuse the differences.
array_project(): too mathematically esoteric
array_select(): potentially also overloaded - what next, array_join()? - but I admit that this is the name I typically use when I write the sort of function that I gave above.

                          ***

One thing about the existing implementation: it doesn't retain the keys of the original array.

This throws away information that might still be needed. It's possible that some elements in the original array didn't supply values to the result (they lacked have the key in question); without the original array's keys to provide a mapping, you won't know which ones they were.

If you did this twice on different keys, then as soon as one result array came up short, the two sets would no longer be reconcilable.

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to