0

Нужно из многомерного массива сделать одномерный. Входной массив

$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 ответа 2

1
$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);
-1

Решил:

$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 и будет выходным массивом

2
  • Тот кто поставил "-1". Сделай лучше 23 авг 2020 в 9:38
  • Ставил не я, но почему - понятно. В этом решении структура массива не та, что в условии. 23 авг 2020 в 11:06

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.