Question

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

Était-ce utile?

La solution

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.');'));

Autres conseils

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top