如何获取数组元素

时间:2014-10-20 12:29:08

标签: php arrays

我有一个数组$ 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
                            )

                    )

            )

如果我想显示"界面"价值,我必须这样做:

echo $data['ProductProperties']['ProductProperty'][0]['interface'];

但在我的情况下,这些数字总是在变化,所以使用上面的方法是不行的。我可以直接选择"界面"没有提及数字索引的价值,例如:

echo $data['ProductProperties']['ProductProperty']['interface'];

提前致谢。 (使用php 5.5)

3 个答案:

答案 0 :(得分:4)

不,你不能像你写的那样。您必须循环遍历整个$data['ProductProperties']['ProductProperty']数组,并检查嵌套数组中是否存在interface键。

答案 1 :(得分:0)

不,但您可以编写函数来获取interface

$interface = getInterFace($data['ProductProperties']['ProductProperty']);

function getInterFace($array) {
   foreach ($array as $element) {
       if (isset($element['interface'])) {
           return $element['interface'];
       }
   }
   return false;
}

答案 2 :(得分:0)

不,你不能手动为它写一个函数。您将不得不遍历要搜索的数组,并使用array_key_exists函数检查该密钥是否存在。

一段可以帮助您的小片段:

foreach($data['ProductProperties']['ProductProperty'] as $array)
  if(array_key_exists("KEY_TO_SEARCH_FOR", $array))
    return $array;