简体   繁体   中英

How to access nested associative array data in PHP

I have an indexed array that contains a nested associative array AND a nested indexed array:

$myArray = array ( 
    0 => array (
        'name' => 'Paul', 
        'age' => '23', 
        'hobbies' => array ( 
            0 => 'basketball',
        ), 
        'pets' => 'dog',
    ),
);

How can I access all of these values and convert them into variables?

You can just access from Array

Write your array like this

$myArray = [
  0 => [
      'name' => 'Paul',
      'age' => '23',
      'hobbies' => [
              0 => 'basketball',
            ],
      'pets' => 'dog'
    ]
];

Suppose you want to access name of first elements

echo $myArray[0]['name']; // it will print 'Paul'
echo $myArray[0]['hobbies'][0]; // it will print basketball

Now you can fetch like above.

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