Skip to content

Instantly share code, notes, and snippets.

@dimmduh
Created February 1, 2018 14:44
Show Gist options
  • Save dimmduh/077b4df7257073d086fde46f0e7483f5 to your computer and use it in GitHub Desktop.
Save dimmduh/077b4df7257073d086fde46f0e7483f5 to your computer and use it in GitHub Desktop.
php - make multidimensional array to flat array path => value
<?php
function flat_array($array, $delimiter = '/')
{
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$subResult = flat_array($value, $delimiter);
foreach ($subResult as $subKey => $subValue) {
$result[$key . $delimiter . $subKey] = $subValue;
}
} else {
$result[$key] = $value;
}
}
return $result;
}
<?php
$example = [
'hello',
'test' => 45,
46 => 333,
'testDeep' => [34, 56, 'rr' => ['sdf' => 33, 55,66,23]],
];
print_r($example);
//result
//Array ( [0] => hello [test] => 45 [46] => 333 [testDeep/0] => 34 [testDeep/1] => 56 [testDeep/rr/sdf] => 33 [testDeep/rr/0] => 55 [testDeep/rr/1] => 66 [testDeep/rr/2] => 23 )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment