Рекурсия array_map
Нужно из многомерного массива сделать одномерный. Входной массив
$arr = [
['type' => 'one', 'test' => 'test1'],
['type' => 'nesting', 'test' => 'test2', 'new' => [
['type' => 'second', 'test' => 'test21'],
['type' => 'second', 'test' => 'test22'],
['type' => 'nesting', 'test' => 'test23', 'new' => [
['type' => 'third', 'test' => 'test231'],
['type' => 'third', 'test' => 'test232']
]],
]],
['type' => 'one', 'test' => 'test3'],
['type' => 'one', 'test' => 'test4'],
['type' => 'one', 'test' => 'test5']
];
На выходе должны получить
[
['type' => 'one', 'test' => 'test1'],
['type' => 'second', 'test' => 'test21'],
['type' => 'second', 'test' => 'test22'],
['type' => 'third', 'test' => 'test231'],
['type' => 'third', 'test' => 'test232'],
['type' => 'one', 'test' => 'test3'],
['type' => 'one', 'test' => 'test4'],
['type' => 'one', 'test' => 'test5']
];
Ответы (2 шт):
Автор решения: Александр Маринов
→ Ссылка
Решил:
$arrRes = [];
$func = function ($item) use (&$func, &$arrRes) {
if ('nesting' === $item['type']) {
return array_map($func, $item['new']);
}
return $arrRes[] = $item;
};
array_map($func, $arr);
$arrRes и будет выходным массивом
Автор решения: Максим Степанов
→ Ссылка
$arr = [
['type' => 'one', 'test' => 'test1'],
['type' => 'nesting', 'test' => 'test2', 'new' => [
['type' => 'second', 'test' => 'test21'],
['type' => 'second', 'test' => 'test22'],
['type' => 'nesting', 'test' => 'test23', 'new' => [
['type' => 'third', 'test' => 'test231'],
['type' => 'third', 'test' => 'test232']
]],
]],
['type' => 'one', 'test' => 'test3'],
['type' => 'one', 'test' => 'test4'],
['type' => 'one', 'test' => 'test5']
];
function getTests($arr)
{
$res = [];
foreach ($arr as $item) {
if (isset($item['new']) && is_array($item['new'])) {
$res = array_merge($res, getTests($item['new']));
} else {
$res[] = $item;
}
}
return $res;
}
$tests = getTests($arr);