現場演示:https://eval.in/88626
試試這個:
創建一個ID一個新的數組作爲這樣的關鍵:
$countries = array(
array('ID' => '8','Country' => 'Finland','Currency' => 'EUR'),
array('ID' => '9','Country' => 'France','Currency' => 'EUR')
);
$outArray = array();
foreach($countries as $country){
$outArray[$country['ID']] = $country;
}
訪問陣列,通過其ID喜歡這
print_r($outArray[8]['Country']);
輸出:
Finland
更新搜索:
現場演示:https://eval.in/88651
$countries = array(
array('ID' => '8','Country' => 'Finland','Currency' => 'EUR'),
array('ID' => '9','Country' => 'France','Currency' => 'EUR')
);
$r1 = getArrayById($countries,8);
$r2 = getArrayById($countries,'Finland');
$r3 = getArrayById($countries,'EUR');
print_r($r1);
print_r($r2);
print_r($r3);
function getArrayById($countries,$val){
$outArray = array();
foreach($countries as $country){
if(in_array($val,$country)){
$outArray[$country['ID']] = $country;
}
}
return $outArray;
}
輸出:
Array
(
[8] => Array
(
[ID] => 8
[Country] => Finland
[Currency] => EUR
)
)
Array
(
[8] => Array
(
[ID] => 8
[Country] => Finland
[Currency] => EUR
)
)
Array
(
[8] => Array
(
[ID] => 8
[Country] => Finland
[Currency] => EUR
)
[9] => Array
(
[ID] => 9
[Country] => France
[Currency] => EUR
)
)
所以你_know_什麼ID是你找誰? –
如果您知道您將始終在尋找什麼值並使用array_keys或array_key_exists(),則可以將某個鍵與每個子數組關聯以便於遍歷。 –
好吧,我希望能夠通過任何鍵(ID,國家,貨幣)來查看元素。 –