I've searched for this on and off for a couple of years to no avail. Occasionally I'd like to prune a multi-dimension to a certain depth. This would be useful when storing large recursive data sets when you only need data to a certain depth and the rest should be discarded.
For example, given the following array:
$arr = array(
'1' => array(
'1.1' => '1.1.1'),
'2',
'3' => array(
'3.1' => array(
'3.1.1' => '3.1.1.1')
)
);
I would want to prune it back to x number of dimensions calling something like this:
some_prune_method($arr array, $dimensions integer)
...and expect data to be returned something like this:
print_r(some_prune_method($arr, 1));
Array(
[
'1',
'2',
'3'
]
)
print_r(some_prune_method($arr, 2));
Array(
[
'1' => ['1.1'],
'2',
'3' => ['3.1']
]
)
print_r(some_prune_method($arr, 3));
Array(
[
'1' => ['1.1'],
'2',
'3' => ['3.1' => '3.1.1']
]
)
I can think how to do this manually using a callback to iterate through the array but that's slow. Ideally this would need to be done WITHOUT iterating through the entire array.
Maybe I'm missing a simple way to do this?
['1' => [...], '2']with depth 1 you want the key of the first item and value of the second. If your inputs looked rather like this:['1' => [...], '2' => []]Then it would be matter of finding out at which level to call array_keys. But since you mix it, you have to keep checking what you have. Anyway if you want to reduce the entire array, you have to traverse the entire array, one way or the other.