gpt4 book ai didi

php - array_filter 与关联数组?

转载 作者:行者123 更新时间:2023-12-02 22:38:16 26 4
gpt4 key购买 nike

我正在使用 array_filter 来做这样的事情:

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

但是例如过滤器中的更多选项

$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"));

或者

$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"));

我怎样才能得到唯一的这个人(以yyear=1989job=prof结尾),我可以使用array_filter吗?或任何内置函数可以做到这一点?

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

或者

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

最佳答案

PHP 5.6 introduces可选标志 ARRAY_FILTER_USE_KEY 允许这样做:

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

$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")
);

$peopleEndingInY = array_filter($people, 'endswithy', ARRAY_FILTER_USE_KEY);

// Outputs: 5
var_dump(count($peopleEndingInY));

如果您需要维护键和值,另一个标志 ARRAY_FILTER_USE_BOTH 将执行此操作,如本示例所示:

$ar = array(
'key1' => 'value1',
'key2' => 'value2'
);

//Note that this doens't actually filter anything since it doesn't return a bool.
$output = array_filter($ar, function($value, $key){
echo sprintf("%s => %s\n", $key, $value);
}, ARRAY_FILTER_USE_BOTH);

关于php - array_filter 与关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6199496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com