简体   繁体   中英

How to get an array element

I have an array $data, here's print_r($data) values:

        [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
                            )

                    )

            )

If i want to display "interface" value, i have to do like that:

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

But in my case these numbers are always changing, so this is a no go for using a method above. Can i choose directly "interface" value without mentioning a number index, eg:

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

Thanks in advance. (using php 5.5)

No, you can't in the way you wrote. You must loop through the whole $data['ProductProperties']['ProductProperty'] array, and check for the existance of interface key in the nested array.

no, but you can write your function to get out the interface

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

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

No, you can't unless you write a function for it manually. You will have to iterate through the array you want to search in and use the array_key_exists function to check for existence of that key.

A little snippet that will help you along the way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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