douqianxun8540 2017-01-26 17:08
浏览 38
已采纳

CakePHP 2.x - Hash :: filter - 如何设置回调函数? // PHP过滤器

I want to filter an array over Hash::filter and use a callback function

static Hash::filter(array $data, $callback = array('Hash', 'filter'))

...You can also supply a custom $callback to filter the array elements... (CakePHP Docs)

My question here is just... How?

Maybe there's a failure in my head with the translations, but i have the JavaScript filter function in mind, where you can filter over an array and give the filterfunction the actual element its iterating over atm. Then if it returns false it gets kicked out of the array.

maybe im just bad with php but.. could anybody help me with it, please? :)

my attempt atm is something like this

$bis_datum = '2017-01-01';
$res = Hash::filter($multidim_assoc_array, function($part_of_multidim_assoc_array){
        return !strtotime($assoc_array['von_datum']) > strtotime($bis_datum);
});

i know there's something very wrong here, because it sais

array('Hash', 'filter')

in the docs and theres just an anonymous function here, but i dont get what the "Hash" and "filter" part means :S

$example = array(

'User' => array(
    0 => array(
        'name' => 'Bob',
        'age' => 25
    ),
    1 => array(
        'name' => 'John',
        'age' => 22
    ),
    2 => array(
        'name' => 'Jen',
        'age' => 32
    )
)

'School' => array(
    'name' => 'Brainslaves High',
    'adress' => 'Somestreet 42'
)
);

as an easy example.. how can i filter this array to kick out everyone whos age is below 25 ?

Thanks-a-lot!

  • 写回答

1条回答 默认 最新

  • douzhengnao8265 2017-01-26 17:24
    关注

    Hash::filter won't help you for your example, you better work with array_filterdirectly

    $res = array('User' => array_filter($example['User'], function($user) {
                        return $user['age'] > 25;
                    })) + array('School' => $example['School']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号