dongyuan1870 2017-05-24 08:30
浏览 33
已采纳

在PHP中映射过滤的数组[重复]

I am trying to map one array, array1, as key to another array, array2. Basically this:

[
    "array1_val1" => [ 
        "array2_val1"=> "creation_time", 
        "array2_val2"=> "creation_time", 
        ... 
    ],
    ...,
]

This is not the problem, the problem is the method I am trying out. As follows:

$div = array_map(function ($value){
    global $files;
    global $value;
    return array_filter($files, function($k){
        // global $value;
        $ex = explode("_", $k);
        var_dump(substr($ex[0], 0, 5)."    ".$value."   ".__LINE__);
        return substr($ex[0], 0, 5) === $value;
    }, ARRAY_FILTER_USE_KEY);
}, $file_names_g);

Definitions:

  • $file_names_g - is an array that has all distinct values (first 5 letters of the file names of $files values)
  • $files - is an array with filename (key) and creation date (value). The filname starts with same 5 letters in $file_names_g and rest differ depending on date the files are created.

Filename example: ABC_24May2017.bak

Now I want the files that start with the same first 5 letters in $file_names_g with $file_names_g being a key and and array with file name as key and creation date as value, (this is the format of the $files array).

Now the problem is that I cannot figure out how to give $value variable access to the function in array_filter. Mentioning it global doesn't help, I get either an empty value or a null. How can I overcome that or is there any better method?

Regards

</div>
  • 写回答

1条回答 默认 最新

  • dte8665 2017-05-24 08:35
    关注

    You can use a variable defined in the outer scope inside a closure function with use:

    $value = 'foo';
    function($k) use ($value) {
         // you can now access the variable value
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站