我有这个数组:
Array (
[0] => Array ( [cast_id] => 45 [character] => Evelyn Salt [credit_id] => 52fe4555c3a368484e054141 [gender] => 1 [id] => 11701 [name] => Angelina Jolie [order] => 0 [profile_path] => /6tocswK39SrSjZIRDaTpVyPxDz8.jpg )
[1] => Array ( [cast_id] => 3 [character] => Theodore Winter [credit_id] => 52fe4555c3a368484e05409f [gender] => 2 [id] => 23626 [name] => Liev Schreiber [order] => 1 [profile_path] => /qFn3npmqd1qaYOk6yohmi3FbPhc.jpg )
[2] => Array ( [cast_id] => 4 [character] => Darryl Peabody [credit_id] => 52fe4555c3a368484e0540a3 [gender] => 2 [id] => 5294 [name] => Chiwetel Ejiofor [order] => 2 [profile_path] => /fwaEgwYJdzGyBmGcHiH13vobQii.jpg )
[3] => Array ( [cast_id] => 10 [character] => Oleg Vasilyevich Orlov [credit_id] => 52fe4555c3a368484e0540bb [gender] => 2 [id] => 7107 [name] => Daniel Olbrychski [order] => 3 [profile_path] => /nfqJ8xiVNyBQQhnYRkwJzl3iS7s.jpg ))
我需要搜索性别= 2的名字。
现在我使用这段代码:
function searcharray($value, $gender, $array) {
foreach ($array as $a => $val) {
if ($val[$gender] == $value) {
return $val['name'];
}
}
return null;
}
$iro = searcharray('2', gender, $array);
但它给了我第一个:Liev Schreiber。 我需要用“,”分隔所有这些。
答案 0 :(得分:2)
试试这个
function searcharray($value, $gender, $array) {
$arrNames = [];
foreach ($array as $a => $val) {
if ($val[$gender] == $value) {
$arrNames[]= $val['name'];
}
}
return $arrNames;
}
答案 1 :(得分:1)
这是因为你在一个循环中间放了一个return语句。这样,第一个匹配将终止函数执行。 为此,您应首先声明一个空结果数组,并将每个匹配值推入其中。在检查了数组的每个元素并且foreach完成后,您可以返回imploded数组以获取用逗号分隔的所有名称。 考虑到这一切,正确的功能如下:
function searcharray($value, $gender, $array) {
$results = [];
foreach ($array as $a => $val) {
if ($val[$gender] == $value) {
array_push($results, $val['name']);
}
}
return implode(',', $results);
}
$iro = searcharray('2', gender, $array);