在PHP中检查数组值是否存在另一个数组键

时间:2014-03-04 11:09:34

标签: php arrays comparison

我有两个具有以下值的数组,

First Array:

Array
(
    [Strongly Agree] => 100
)

第二阵列:

Array
(
    [0] => Strongly Agree
    [1] => Agree
    [2] => Neither Agree or Disagree
    [3] => Strongly Disagree
)

我需要输出就像这样,

Array (
        [0] => 100
        [1] => 0
        [2] => 0
        [3] => 0
)

3 个答案:

答案 0 :(得分:2)

尝试

foreach($array2 as $key => $value) {
   $temp = array_key_exists($value, $array2) ? $array1[$value] : 0;
   $newArr[$key] = $temp;
}

答案 1 :(得分:2)

存在数组键不会触发通知

$sample = array('Strongly Agree' => 100);
$alternatives = array(   'Strongly Agree',    'Agree',    'Neither Agree or Disagree',    'Strongly Disagree');
$output=array();
foreach($alternatives as $alternative) {
    $output[$alternative] = array_key_exists($alternative, $sample)? $sample[$alternative]:0;
}

print_r($output);

答案 2 :(得分:0)

尝试

$arr2 = array_merge(array_fill_keys($arr2, 0), $arr1);

请参阅演示here