PHP从嵌套数组中获取值

时间:2017-03-06 18:38:11

标签: php arrays

我试图从'嵌套数组'中获取'name'值我不确定这是否是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 
        ) 
    }

我正在尝试访问数组中每个项目的“name”键,但很难做到。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

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

测试用例:

>>> 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",
   ]
>>> 

答案 1 :(得分:0)

您可以这样做:

initGoolgeChart : function() {
    // Load the Visualization API and the corechart package.
    google.charts.load("current", {"packages": ["bar"] });

    // Set a callback to run when the Google Visualization API is loaded.
    google.charts.setOnLoadCallback(MigrationMonitor.drawCharts);
},

drawCharts : function() {
    if(MigrationMonitor.dynamicFields.chartData != null && MigrationMonitor.dynamicFields.chartData.length > 0) {

        var data = google.visualization.arrayToDataTable(MigrationMonitor.dynamicFields.chartData);

        // won't work, don't know how i can add steps here then...
        // data.addColumn({type:"string", role: "tooltip"});

        // // Set chart options
        var options = {
            chart : {
                title : "Build: " + MigrationMonitor.dynamicFields.chartTitle[1] + " VS " + MigrationMonitor.dynamicFields.chartTitle[2]
            }
        };

        var chart = new google.charts.Bar(document.getElementById('charDiv'));
        chart.draw(data, options);
    }
}