多维数组,叶子作为父项的键。递归迭代器

时间:2015-07-01 19:48:41

标签: php

您好我需要将包含子数据的父项的多维数组结构更改为包含父母信息的子项

$tab = [
        'movies' => [
            'action',
            'drama', 
            'comedy' => [
                'romance' => ['90th'],
                'boring'
            ]
        ],
        'colors' => [
            'red'=>'light',
            'green'=> [
                'dark',
                'light'
            ],
            'oragne'
        ]
    ];

转移到

        $tab = [
        '90th' => [
            'romance' => [
                'comedy' => 'movies'
            ] 
        ],
        'boring' => [
            'comedy' => 'movies'
        ],
        'comedy' => 'movies',
        'drama' => 'movies',
        'action' => 'movies',
        'light' => [
            'red',
            'green' => 'colors'
        ],
        'dark' => [
            'green' => 'colors'
        ],
        'oragne' => 'colors',
        'green' => 'colors',
        'red'
    ];

我知道为了获得叶子,我可以使用

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($tab), RecursiveIteratorIterator::LEAVES_ONLY) as $key => $value) {

        $result[$value] = $key;
    }

但它没有像我期望的那样起作用。

1 个答案:

答案 0 :(得分:0)

这是一个非常局部的答案,所以不要抱有希望。它可以扩展以解决您的问题。

要实现此功能,首先需要'red'=>'light''red'=>['light'}(所以它看起来像'romance' => ['90th'])。然后它会为您提供一系列平面阵列,而不是您想要的深度。此外,它不像您想要的输出那样排序。

function insideOut($array, $trail) {

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

    $new_trail = $trail;

    if(is_array($value)) {
      $new_trail[] = $key;
      insideOut($array[$key], $new_trail);
    }
    else {
      $new_trail[] = $value;
      print_r($new_trail);
    }

  }

}

insideOut($tab, array());

这给出了以下输出:

Array
(
    [0] => movies
    [1] => action
)
Array
(
    [0] => movies
    [1] => drama
)
Array
(
    [0] => movies
    [1] => comedy
    [2] => romance
    [3] => 90th
)
Array
(
    [0] => movies
    [1] => comedy
    [2] => boring
)
Array
(
    [0] => colors
    [1] => red
    [2] => light
)
Array
(
    [0] => colors
    [1] => green
    [2] => dark
)
Array
(
    [0] => colors
    [1] => green
    [2] => light
)
Array
(
    [0] => colors
    [1] => oragne
)

如果您可以使用提供“深度”跟踪的内容替换print_r($new_trail);然后将其保存,则问题将得到解决。

我知道,我知道,答案不多,我不希望进行绿色检查。但我认为最好在这里发布我的(非常少的)进展,而不是扔掉它。