简体   繁体   English

PHP多维关联数组-如何获取键列表?

[英]PHP Multidimensional Associative Array - how to get list of keys?

Here is an example of my data: 这是我的数据的示例:

[204] => Array
    (
        [1] => Array
            (
                [leads] => 9
            )

        [2] => Array
            (
                [leads] => 15
            )

    )

[200] => Array
    (
        [1] => Array
            (
                [leads] => 7
            )

        [2] => Array
            (
                [leads] => 16
            )

        [3] => Array
            (
                [leads] => 5
            )

    )

I am at the stage where I trying to output the array data into a table but how do I set up the table headers dynamically so that the columns will be 1 | 2 | 3 我正在尝试将数组数据输出到表中的阶段,但是如何动态设置表头,以使列为1 | 2 | 3 1 | 2 | 3 1 | 2 | 3 , even if some subsets don't have an array of that type? 1 | 2 | 3 ,即使某些子集没有该类型的数组?

The array is constructed from the results of a database query like so: 该数组是根据数据库查询的结果构建的,如下所示:

$dailytotals[$store][$campaigntypeid] = array('leads'=> $leads);

I tried a for each but just realised that it wouldn't work since not all subsets have all columns. 我为每一个都尝试了一个,但是才意识到这是行不通的,因为并非所有子集都具有所有列。

Is there a way to get what I am trying to find? 有没有办法找到我要寻找的东西?

Try this 尝试这个

$columns = array();
foreach ($your_array as $key=> $arr) {
  $columns = array_unique(array_merge($columns, array_keys($arr)));
}

Another way 其他方式

$columns = array_reduce($your_array, 
  function ($r, $val) { 
    return array_unique(array_merge($r, array_keys($val))); 
  }, 
  array()
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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