简体   繁体   中英

array_map to simplify array, what am I doing wrong?

I have a function which returns an array of arrays when querying a table, each 'subarray' is a row in the table, now I want to create a 'fetchColumn' function to transform my resulting array from this:

Array(
    [0] => Array(
        'column' => 'value'
    )
    [1] => Array(
        'column' => 'value'
    )
    [2] => Array(
        'column' => 'value'
    )
)

Into this:

Array(
    [0]=>value
    [1]=>value
    [2]=>value
)

Here is the function:

public static function fetchColumn($column)
    {
        $callback = function($value){
            return $value[$column];
        };        
        return array_map($callback,$array); // $array exists
    }

I get:

Array
(
    [0] =>
    [1] =>
    [2] =>
)

You aren't importing $column into your lambda:

$callback = function($value) use ($column) {
    return $value[$column];
};       

Edit This assumes that you are calling the function fetchColumn('column') , and that $array really does exist within the context of fetchColumn . In your code, it doesn't...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM