繁体   English   中英

如何获得数组元素

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM