简体   繁体   中英

Putting array_filter() in a function

I would like to transform the code below in a function

function filter($row){return ($row['id_menu'] == 10);}

$matches = array_filter($array_mostrar_privilegios, "filter");
foreach ($matches as $element)
{
    echo $element['consultar'];
}

like

function filter($row, $num)
{
    return ($row['id_menu'] == $num);
}
function find($my_array, $num)
{
    $matches = array_filter($my_array, "filter($row, $num)");
    foreach ($matches as $element)
    {
        return $element['consultar'];
    }
}

but i don't how to make it work

If you have PHP 5.3+, then there is no need to use a string as the callback parameter. PHP 5.3+ has anonymous functions.

$matches = array_filter($my_array, function($row) use($num){
    return filter($row, $num);
});

If you do not have PHP 5.3, then you can use create_function ( warning : this uses eval() ):

$matches = array_filter($my_array, create_function('$row', 'return filter($row,'.$num.');'));

Using closures:

function find($my_array, $num)
{
    $matches = array_filter(
        $my_array, 
        function filter($row) use($num) {
            return ($row['id_menu'] == $num);
        }
    );
    foreach ($matches as $element)
    {
        return $element['consultar'];
    }
}

except that your return inside the foreach will only return the first element from $matches

If you expect multiple $matches values, and want to return them all, consider using yield to turn this into a generator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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