【问题标题】:Variable leveled multi-dimensionaled array to value 'flattend' array with PHP? [duplicate]可变水平多维数组用PHP值'展平'数组? [复制]
【发布时间】:2018-03-31 13:40:04
【问题描述】:

我正在寻找一种解决方案来展平可变多维数组,以将最后一个可用数组中的所有值展平为单个 Array[](包含多维数组中每个最后一个数组的数据集)。

感谢任何帮助!

与其他问题不同

因为结束结果应该是所有Arrays的集合,包含:

array(
    'title' => xx,
    'id' => xx
)

在不同的多维数组中列出。 不同的项目都有固定的keys:title和id。

样本基数组

$data = array(
    array(
        'title' => xx,
        'id' => xx
    ),
    array(
        array(
            array(
                'title' => xx,
                'id' => xx
            ),
            array(
                'title' => xx
                'id' => xx
            )
        )
    ),
    array(
        array(
            array(
                array(
                    'title' => xx,
                    'id' => xx
                ),
                array(
                    'title' => xx,
                    'id' => xx
                ),
                array(
                    'title' => xx,
                    'id' => xx
                )
            )
        ),
        array(
            'title' => xx,
            'id' => xx
        ),
        array(
            array(
                array(
                    array(
                        'title' => xx,
                        'id' => xx
                    )
                )
            )
        )
    )
);

应该展平为

 $data = array(
    array(
        'title' => xx,
        'id' => xx
    ),
    array(
        'title' => xx,
        'id' => xx
    ),
    array(
        'title' => xx,
        'id' => xx
    ),
    array(
        'title' => xx,
        'id' => xx
    ),
    array(
        'title' => xx,
        'id' => xx
    ),
    array(
        'title' => xx,
        'id' => xx
    ),
    array(
        'title' => xx,
        'id' => xx
    ),
    array(
        'title' => xx,
        'id' => xx
    )
);

【问题讨论】:

  • 这不是那个问题的重复...。这将每个key 实体的数组弄平...我希望保留key/values 的数组...
  • 有hundreds of "flatten array" questions。你具体尝试了什么,你坚持什么,你的问题与其他人有什么不同?
  • idownvotedbecau.se/noattempt 和 idownvotedbecau.se/nocode。帮助你自己,我们会看看你的尝试。读取数组的 foreach 和 is_array 以了解该值是数组还是字符串。下一个数组,否则保留键和值。

标签: php arrays flatten


【解决方案1】:
function flatten_array(&$data) {

    foreach ($data as $index => &$item) {

        if(has_array_child($item)) {
            unset($data[$index]);
            flatten_array($item);
            $data = array_merge($data, $item);
        }

    }

}

function has_array_child($item) {
    foreach($item as $child) {
        if(is_array($child)) {
            return TRUE;
        }
    }

    return FALSE;
}

flatten_array($data);

print_r($data);

【讨论】:

  • 是的,完美!非常感谢!根据需要!
  • 没必要,$data 通过引用传递。
  • 我的错,忽略了那个!再次感谢..
猜你喜欢
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
  • 2013-09-12
  • 2012-08-27
  • 2019-07-30
  • 1970-01-01
  • 1970-01-01
  • 2011-07-26
相关资源
最近更新 更多