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

报告相同问题?