仅使用键的多维数组到文本

时间:2018-01-19 14:40:45

标签: php arrays multidimensional-array

我有一个这样的数组:

$array = [
        "Darren" => [
            "age" => "18",
            "work" => [
                "occupation" => "developer",
                "company" => "ABC Ltd"
            ]
        ],
        "John" => [
            "age" => "24",
            "work" => [
                "occupation" => "developer",
                "company" => "ABC Ltd",
                "url" => "www.example.com"
            ],
        ]
    ]

并且希望将键与中间的点合并,具体取决于数组的层次结构:

       "Darren.age"
       "Darren.work.occupation"
       "Darren.work.company"
       ...

我到目前为止所做的功能是

    public function buildExpressionKey($array, $parentKey = null){

        $expression = [];

        foreach($array as $key=>$value){

            if(is_array($value)){
               array_push($expression, $parentKey. implode(".", 
$this->buildExpressionKey($value, $key)));
           }else{
               array_push($expression, $key);
           }
       }

       return $expression;
   }

目前正在返回此值:

  [
    [0] => "age.Darrenoccupation.company"
    [1] => "age.Johnoccupation.company.url"
  ]

想知道是否可以制作一个自动合并这样的键的功能,提前谢谢:)

2 个答案:

答案 0 :(得分:1)

您目前要求的是:

<?php

$people =
[
 'John' => 
    [
        'Occupation' => 'Developer',
        'Age' => 18
    ],
'Darren' =>
    [
        'Occupation' => 'Manager',
        'Age' => 40
    ]
];


foreach($people as $name => $value)
    foreach($value as $k => $v)
        $strings[] = $name . '.' . $k;

var_export($strings);

输出:

array (
  0 => 'John.Occupation',
  1 => 'John.Age',
  2 => 'Darren.Occupation',
  3 => 'Darren.Age',
)

答案 1 :(得分:0)

管理以解决此问题:)

/**
 * @param $array
 * @return array
 */
public function buildExpressionKey($array){

    $iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array));
    $keys = array();
    foreach ($iterator as $key => $value) {
        // Build long key name based on parent keys
        for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
            $key = $iterator->getSubIterator($i)->key() . '.' . $key;
        }
        $keys[] = $key;
    }
    return $keys;
}

在此处找到类似的内容:Get array's key recursively and create underscore separated string