PHP :: Aufgabe #282

2 Lösungen Lösungen öffentlich

Mehrdimensional zu Eindimensional

Anfänger - PHP von Exception - 11.05.2020 um 08:38 Uhr
Das folgende mehrdimensionale Array soll zu einem flachen, eindimensionalen Array umgewandelt werden. Viel Spaß.
Quellcode ausblenden PHP-Code
$a = [
	0 => 'Text 0',
	1 => 'Text 1',
	2 => 'Text 2',
	'A' => [
		0 => 'Text A 0',
		1 => 'Text A 1',
		2 => 'Text A 2',
	],
	'B' => [
		'A' => [
			0 => 'Text B A 0',
			1 => 'Text B A 1',
			2 => 'Text B A 2',
		]
	]
];


Lösungen:

vote_ok
von juergen (360 Punkte) - 04.06.2020 um 20:21 Uhr
Quellcode ausblenden PHP-Code
$a = [
    0 => 'Text 0',
    1 => 'Text 1',
    2 => 'Text 2',
    'A' => [
        0 => 'Text A 0',
        1 => 'Text A 1',
        2 => 'Text A 2',
    ],
    'B' => [
        'A' => [
            0 => 'Text B A 0',
            1 => 'Text B A 1',
            2 => 'Text B A 2',
        ]
    ]
];

function flatten(array $array = []){
  if($array){
    $result = [];
    foreach($array as $key=>$arr){
      if(is_array($arr)){
        $result = array_merge($result,flatten($arr));
      } else {
        $result[$key] = $arr;
      }
    }
    return $result;
  }
}

print_r(flatten($a));
vote_ok
von Exception (7090 Punkte) - 28.08.2020 um 13:41 Uhr
Quellcode ausblenden PHP-Code
$a = [
    0 => 'Text 0',
    1 => 'Text 1',
    2 => 'Text 2',
    'A' => [
        0 => 'Text A 0',
        1 => 'Text A 1',
        2 => 'Text A 2',
    ],
    'B' => [
        'A' => [
            0 => 'Text B A 0',
            1 => 'Text B A 1',
            2 => 'Text B A 2',
        ]
    ]
];

print_r(flattenMultidimensionalArray($a));
Quellcode ausblenden PHP-Code
function flattenMultidimensionalArray(array $haystack): array
{
  $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack));
  return iterator_to_array($iterator, false);
}


After method call

Konsolenausgabe:

Array
(
[0] => Text 0
[1] => Text 1
[2] => Text 2
[3] => Text A 0
[4] => Text A 1
[5] => Text A 2
[6] => Text B A 0
[7] => Text B A 1
[8] => Text B A 2
)