如何从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?

例如,如果我有以下数组: p>

  $ 号码=阵列(
 “A”=> $值1,
 “B”=> $值2,
 “C”=> $值3,
 “个d”=> $ VALUE4,
  “E”=> $值5,
 “F”=> $ value6,
 “G”=> $ value7,
)的; 
 代码>  PRE> 
 
 如果某些值变量等于0且其余值等于1,我如何选择值相等的键,例如0? p> 
  div>

$result = [];

foreach($numbers as $id => $number) {

     if($number ==0)
         $result[$id] = $number;

}

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