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']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分