[英]How to get an array element
我有一個數組$ data,這是print_r($data)
值:
[ProductProperties] => Array
(
[ProductProperty] => Array
(
[0] => Array
(
[Additionaldescription] => microphone, blabla
)
[1] => Array
(
[interface] => USB 2.0
)
[2] => Array
(
[Model] => C310 HD
)
[3] => Array
(
[Manufacturer] => Logitech
)
[4] => Array
(
[Color] => Black
)
)
)
如果我想顯示“ interface”值,我必須這樣做:
echo $data['ProductProperties']['ProductProperty'][0]['interface'];
但就我而言,這些數字一直在變化,因此使用上述方法絕對不可行。 我可以直接選擇“接口”值而不提及數字索引嗎,例如:
echo $data['ProductProperties']['ProductProperty']['interface'];
提前致謝。 (使用PHP 5.5)
不,您無法按照自己的方式寫作。 您必須遍歷整個$data['ProductProperties']['ProductProperty']
數組,並檢查嵌套數組中interface
鍵是否存在。
否,但是您可以編寫函數以退出interface
$interface = getInterFace($data['ProductProperties']['ProductProperty']);
function getInterFace($array) {
foreach ($array as $element) {
if (isset($element['interface'])) {
return $element['interface'];
}
}
return false;
}
不可以,除非您手動為其編寫函數。 您將不得不遍歷要搜索的數組,並使用array_key_exists
函數檢查該鍵的存在。
一個小片段將對您有幫助:
foreach($data['ProductProperties']['ProductProperty'] as $array)
if(array_key_exists("KEY_TO_SEARCH_FOR", $array))
return $array;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.