Skip to content

Instantly share code, notes, and snippets.

@SeanCannon
Last active October 28, 2024 18:01
Show Gist options
  • Save SeanCannon/6585889 to your computer and use it in GitHub Desktop.
Save SeanCannon/6585889 to your computer and use it in GitHub Desktop.
PHP array_flatten() function. Convert a multi-dimensional array into a single-dimensional array.
<?php
/**
* Convert a multi-dimensional array into a single-dimensional array.
* @author Sean Cannon, LitmusBox.com | seanc@litmusbox.com
* @param array $array The multi-dimensional array.
* @return array
*/
function array_flatten($array) {
if (!is_array($array)) {
return false;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
} else {
$result = array_merge($result, array($key => $value));
}
}
return $result;
}
@brandonmcconnell
Copy link

@graceman9 What data produces an unexpected result?

For infinite depth, just use -1

@graceman9
Copy link

@brandonmcconnell Have you noticed the difference?

{
    "a": "value1",
    "b_c": "value1.1",
}

and

{
    "a": "value1",
    "c": "value1.1",
}

@brandonmcconnell
Copy link

@graceman9 Oh you want the keys to be concatenated, so every key keeps the log of its original path. Yeah, you are correct that my version does not do that. I tried to follow the approach common in other languages. 🙂

@boedy
Copy link

boedy commented Apr 26, 2024

For a simple 2D array:

$multiDimArray = [[1, 2], [3, 4], [5, 6]];
$flatArray = array_reduce($multiDimArray, 'array_merge', []);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment