2014-03-04 85 views
0

我有兩個陣列具有以下值另一個數組鍵,檢查一個數組值exsits在PHP

第一陣列:

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 
) 

回答

2

嘗試像

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

這需要拼命改進。對於一個它會產生'null'而不是零,它也會發出通知。不要使用這樣的代碼。 – Jon

+1

感謝它的工作...... – Basith

+0

@Jon對不起,其實我意識到我提交了我的答覆。感謝您的建議 – Gautam3164

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

嘗試

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

觀看演示here