2011-10-13 23 views
1

我有這樣問題與PHP數組()

Array ( 
[DISEASE] => Array ([0] => DM [1] => HT) 
[DRUG] => Array ([0] => INSULIN [1] => DIURETIC) 
) 

一個PHP陣列輸出現在我想打印以下

For Disease DM, INSULIN is used 
For Disease HT, DIURETIC is used 

即我想匹配來自陣列疾病與價值藥物。 請幫幫我。

編輯

我不能在這裏找到了 「謝謝」 按鈕。感謝大家的幫助。

回答

4

你爲什麼不使用按鍵陣列中的? http://php.net/manual/en/language.types.array.php(見例如一個)

則數組將類似於:

$items = array(
    array('disease' => 'DM', 'drug' => 'INSULIN'), 
    array('disease' => 'HT', 'drug' => 'DIURETIC'), 
); 

而且你可以把它想:

foreach($items as $item) 
{ 
    echo $item['disease'] . ' - ' . $item['drug']; 
} 
+0

+1好的建議,這可以用'array_combine'在這種情況下很容易實現,[見我的答案](http://stackoverflow.com/questions/7752729/issue-with-php-array/7753078#7753078 ) – hakre

1

假設兩個數組具有相同的長度,你可以做這樣的事情:

for ($i=0; $i < sizeof($yourarray['DISEASE']); ++$i) { 
    echo 'For Disease ', $yourarray['DISEASE'][$i], ', '; 
    echo $yourarray['DRUG'][$i], ' is used'; 
} 
+0

這不起作用,因爲當你應該計算內部數組時,你要計算外部數組 – JohnP

+0

當然,你是對的。抱歉。 :) 修復。OMG! –

+2

OMG!不要每次都計算大小!使用'for($ i = 0,$ s = sizeof($ yourarray ['DISEASE']); $ i <$ s; ++ $ i)'反而 – RiaD

2

陣列指向其價值的關鍵。因此,您的密鑰是DISEASE和DRUG,每個密鑰都是0和1.因此 - 我們正在匹配鍵而不是值。

有很多方法可以打印數組。這是我很難承擔打印這些價值觀對未來的最靈活的方式,但這裏有一個辦法:

foreach ($items['DISEASE'] as $id => $disease) 
{ 
    echo 'For Disease ' . $disease . ', ' . $items['DRUG'][$id] . ' is used'."\n"; 
} 

關鍵的$ id被用來在疾病和藥物子一陽指之間的匹配。

0

[DISEASE] => Array ([0] => DM [1] => HT) 

包含你的鑰匙。

[DRUG] => Array ([0] => INSULIN [1] => DIURETIC) 

包含根據值。

假設你的陣列將被命名爲$array,你可以結合兩種:

$mapped = array_combine($array['DISEASE'], $array['DRUG']); 

然後你就可以通過按鍵來訪問每個藥物的疾病:

$mapped['DM']; # INSULIN 

要打印所有,只是想迭代

foreach($array['DISEASE'] as $disease) 
{ 
    $drug = $mapped[$disease] 
    echo "For Disease $disease, $drug is used.\n"; 
} 
0

這裏有個訣竅:你可能會得到這個觀點並且可以解決你的問題lem

$an = array(
     'numbers'=>array(1,2,3,4,5), 
     'alphabates'=>array('a','b','c','d','e') 
    ); 

foreach($an['numbers'] as $key=>$value){ 
    echo $value." => ".$an['alphabates'][$key]."<br>"; 
}