newbie newbie - 2 months ago 7
PHP Question

array_filter with assoc array?

I am using array_filter to do something like this:

function endswithy($value) {
return (substr($value, -1) == 'y');
}

$people = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe");
$withy = array_filter($people, "endswithy");
var_dump($withy);


BUT with the more option in filter for example

$people = array(
"Johnny"=>array("year"=>1989, "job"=>"prof"),
"Timmy"=>array("year"=>1989, "job"=>"std"),
"Bobby"=>array("year"=>1988),
"Sam"=>array("year"=>1983),
"Tammy"=>array("year"=>1985),
"Danny"=>array("year"=>1983),
"Joe"=>array("year"=>1989,"job"=>"prof"));


OR

$people = array(
array("name"=>"Johnny","year"=>1989, "job"=>"prof"),
array("name"=>"Timmy","year"=>1989, "job"=>"std"),
array("name"=>"Bobby""year"=>1988),
array("name"=>"Sam","year"=>1983),
array("name"=>"Tammy","year"=>1985),
array("name"="Danny","year"=>1983),
array("name"="Joe","year"=>1989,"job"=>"prof"));


How Can I got the only this people (endwith
y
and
year=1989
and
job=prof
) ,Can I use array_filter?
or any build-in function to do this?

$people = array(
"Johnny"=>array("year"=>1989, "job"=>"prof")
);


OR

$people = array(
array("name="Johnny","year"=>1989, "job"=>"prof")
);

Answer

Either use foreach with your current array's structure:

$people = array(
    "Johnny" => array("year" => 1989, "job" => "prof"),
    "Timmy"  => array("year" => 1989, "job" => "std"),
    "Bobby"  => array("year" => 1988),
    "Sam"    => array("year" => 1983),
    "Tammy"  => array("year" => 1985),
    "Danny"  => array("year" => 1983),
    "Joe"    => array("year" => 1989, "job" => "prof"),
);

foreach ( $people as $name => $info ) {
    if ( substr($name, -1) !== 'y' || $info['year'] != 1989 ) {
        unset($people[$name]);
    }
}

print_r($people);

// output:
Array
(
    [Johnny] => Array
        (
            [year] => 1989
            [job] => prof
        )
    [Timmy] => Array
        (
            [year] => 1989
            [job] => std
        )
)

Or convert your array so that name is value of inner array:

$people = array(
    array('name' => 'Johnny', 'year' => 1989, 'job' => 'prof'),
    array('name' => 'Timmy' , 'year' => 1989, 'job' => 'std'),
    array('name' => 'Bobby' , 'year' => 1988),
    array('name' => 'Sam'   , 'year' => 1983),
    array('name' => 'Tammy' , 'year' => 1985),
    array('name' => 'Danny' , 'year' => 1983),
    array('name' => 'Joe'   , 'year' => 1989, 'job' => 'prof'),
);

function filter($item) {
    return substr($item['name'], -1) === 'y' && $item['year'] == 1989;
}

$filteredPeople = array_filter($people, 'filter');

print_r($filteredPeople);

// output:
Array
(
    [0] => Array
        (
            [name] => Johnny
            [year] => 1989
            [job] => prof
        )
    [1] => Array
        (
            [name] => Timmy
            [year] => 1989
            [job] => std
        )
)