扁平化数组,同时在PHP中保留键值对 [英] Flatten array while preserving key value pairs in PHP

查看:108
本文介绍了扁平化数组,同时在PHP中保留键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组:

I have an array like this:

array (size=4)
  0 =>
    array (size=4)
      key => value
      key => value
      key => value
      key => value
  1 =>
    array (size=2)
      key => value
      key => value
  2 =>
    array (size=1)
      key => value
  3 =>
    array (size=1)
      key => value

我想将数组展平为这样:

I want to flatten the array to be this:

array (size=4)
  key => value
  key => value
  key => value
  key => value
  key => value
  key => value
  key => value
  key => value

我已经尝试过使用 array_merge array_walk_recursive RecursiveIteratorIterator RecursiveArrayIterator 之类的解决方案.我也尝试过在StackOverflow上针对类似问题发布的许多解决方案,但是它们都无法按我期望的方式工作.它们要么不保留键值对,要么给我一个与原始数组相同的数组.我的尝试看起来像这样:

I have tried my own solutions using things like array_merge, array_walk_recursive, and RecursiveIteratorIterator with RecursiveArrayIterator. I also tried many of the solutions posted on similar questions on StackOverflow, but none of them work the way I would expect. They either do not preserve the key value pairs, or they give me an array that is identical to the original. My attempts look something like this:

$multidimensionalArray = array(stuff goes here);
$flatArray = array();

function flattenArray ($array) {
  foreach ($array as $key => $value) {
    if (is_array($value) {
      flattenArray($value);
    }
    else {
      $flatArray[$key] = $value;
    }
  }
}

flattenArray($multidimensionalArray);

推荐答案

我想知道 RecursiveArrayIterator 可能会出什么问题,因为您只需要使用最简单的方法从迭代器中收集键/值对 foreach 循环:

I wonder what could go wrong with RecursiveArrayIterator, because you only needed to collect the key/value pairs from the iterator using the simplest foreach loop:

$a = [
  0 => ['a' => 1, 'b' => 2],
  1 => ['x' => 3, 'y' => 4],
  2 => 5,
  3 => ['m' => 6, ['k' => 7, 'n' => 8]],
];

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));

foreach ($it as $key => $value) {
  $result[$key] = $value;
}

print_r($result);

输出:

Array
(
    [a] => 1
    [b] => 2
    [x] => 3
    [y] => 4
    [2] => 5
    [m] => 6
    [k] => 7
    [n] => 8
)

这篇关于扁平化数组,同时在PHP中保留键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆