简体   繁体   English

array_map简化数组,我在做什么错?

[英]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: 我有一个函数可以在查询表时返回数组数组,每个“子数组”都是表中的一行,现在我想创建一个“ fetchColumn”函数来从中转换结果数组:

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: 您不会将$column导入到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 . 编辑这是假设你调用的函数fetchColumn('column')$array 确实的上下文中存在fetchColumn In your code, it doesn't... 在您的代码中,它不会...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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