php: array_filter and callback function
by Pascal Opitz on April 20 2006, 09:48
Sometimes array_pop is just not enough. You might have to strip out something from an array that is 2 dimensional or do some more complicated adjustments to the array values. In this case you can use array_filter and a callback function.
The following example is class based:
<?
class test
{
function test()
{
$arr = array();
$arr[] = array('ID' => 1, 'name' => 'first');
$arr[] = array('ID' => 2, 'name' => 'second');
print_r($arr);
$arr = array_filter($arr, array(&$this, "filter"));
print_r($arr);
}
function filter($var)
{
return($var['name'] != 'first');
}
}
$test = new test();
?>
Comments
by Pascal Opitz on April 21 2006, 02:33 #
is this definition also working in php5?
by fanatique on April 20 2006, 16:06 #
The array is very multidimentional, like this:
$array[‘id’][‘category’][‘element’] = value.
So i want to filter out all the ID’s wich don’t have the good Value in [‘category’][‘element’], how can i do this?
couse the callback function only has $var, i cant give all the $ID’s:
function filter($var)
{
return($var[’$id’] == ’$askedvalue’);
}
would work, but how can i add $id/$askedvalue in the array_filter($array, ‘callbackfunction’)?
by Foleor on November 4 2006, 14:16 #
by Pascal Opitz on November 6 2006, 11:06 #
function filter_str($string, $page=’’)
{
if ($page == ‘’)
$filter = ereg_replace(’[^a-zA-Z0-9_]’, ‘’, $string);
else
$filter = ereg_replace(”[^a-zA-Z0-9_$page]”, ‘’, $string);
return $filter;
}
$page = filter_str($page);
and my array loop
$array = file(“menudata.txt”);//holds menu link names
foreach($array as $page) {
echo “li a href=”index.php?page=$page”{$page}/a/li>”;
(i had to take the link lesser/greater tags out in this post to get them to show up.)
for the life of me I cannot figure out how to make it work.
Thanks for any help you have time to provide.
Karen
by Karen on January 6 2008, 10:12 #