如何获得一个数组元素
问题描述:
我有一个数组$的数据,这里的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
)
)
)
如果我想显示“接口”的价值,我必须做这样的:
echo $data['ProductProperties']['ProductProperty'][0]['interface'];
但在我的情况下,这些数字总是在变化,所以使用上述方法是不行的。我可以直接选择“界面”值而不提及数字索引,例如:
echo $data['ProductProperties']['ProductProperty']['interface'];
在此先感谢。 (使用php 5.5)
答
不,你不能,除非你手动编写一个函数它。您将不得不遍历要搜索的数组,并使用array_key_exists
函数来检查该密钥的存在。
一个小片段,这将帮助你前进的道路:
foreach($data['ProductProperties']['ProductProperty'] as $array)
if(array_key_exists("KEY_TO_SEARCH_FOR", $array))
return $array;
答
不,你不能以你写的方式。您必须遍历整个$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;
}