Question

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] =>
)
Was it helpful?

Solution

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...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top