dp13668681869
dp13668681869
2014-11-20 18:57

如何从PHP中的数组中选择等于某个特定值的键?

已采纳

for example if i have the following array:

$numbers=array(
"A"=>$value1,
"B"=>$value2,
"C"=>$value3,
"D"=>$value4,
"E"=>$value5,
"F"=>$value6,
"G"=>$value7,
);

and if some of the value variables are equal to 0 and the rest are equal to 1, how can I select the keys which values are equal, for example to 0?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duanan2732 duanan2732 7年前
    $result = [];
    
    foreach($numbers as $id => $number) {
    
         if($number ==0)
             $result[$id] = $number;
    
    }
    
    点赞 评论 复制链接分享
  • dtujfmfs06058 dtujfmfs06058 7年前

    Try this:

    $all_zeros = array_filter($numbers);
    $all_ones = array_diff($numbers, $all_zeros);
    

    Also you might use a custom filter function like below:

    function custom_filter($numbers, $targetValue) {
        return array_filter($numbers, function ($i) use ($targetValue) {
            return $targetValue == $i;
        });
    }
    

    Ref:

    1. array_filter
    2. array_intersect
    3. PHP Anonymous function
    点赞 评论 复制链接分享

相关推荐