简体   繁体   中英

PHP Getting Values From Nested Array

I am trying to get the 'name' value from within a 'nested array' I am not sure if thats the correct term in PHP.

   Array ( 
        [0] => Array 
        ( 
            [event] => Array 
                ( 
                    [id] => 28140972 
                    [name] => Northwich v Lincoln United FC 
                    [countryCode] => GB 
                    [timezone] => Europe/London 
                    [openDate] => 2017-03-08T19:45:00.000Z 
                ) 
                [marketCount] => 24 
        ) 
        [1] => Array 
        ( 
            [event] => Array 
                ( 
                    [id] => 28140974 
                    [name] => Viimsi MRJK v Paide Linnameeskond II 
                    [countryCode] => EE 
                    [timezone] => Europe/London 
                    [openDate] => 2017-03-08T17:00:00.000Z 
                ) 
                [marketCount] => 24 
        ) 
    }

I am trying to access the 'name' key of every item in the array, but struggling to do it. Any advice?

$arrayOfNames = array_map(function ($item) {
    return $item['event']['name'];
}, $yourPreviousArray);

Test case:

>>> print_r($data)
Array
(
    [0] => Array
        (
            [event] => Array
                (
                    [id] => 1
                    [name] => James
                )

        )

    [1] => Array
        (
            [event] => Array
                (
                    [id] => 2
                    [name] => Jim
                )

        )

)
=> true
>>> array_map(function($item) {
... return $item['event']['name'];
... }, $data)
=> [
     "James",
     "Jim",
   ]
>>> 

You can do something like this:

foreach ($array as $item) {
    echo $item['event']['name'].'<br/>';
}

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