S
S
Shlorpian2022-04-18 17:10:27
PHP
Shlorpian, 2022-04-18 17:10:27

How to simplify nested loops?

Using the getParsedBody() method in Slim3, I get parameters from multipart/form-data in this form:
Countries[0][City]
Need to be converted to this form:
Countries[0].City

Using nested loops, this is easy, but how to simplify?

foreach ($params as $key => $param) {
    if (!is_array($param)) {
        $data[$key] = $param;
    } else {
        foreach ($param as $key2 => $param2) {
            if (!is_array($param2)) {
                $data[$key . '[' . $key2 . ']'] = $param2;
            } else {
                foreach ($param2 as $key3 => $param3) {
                    if (!is_array($param3)) {
                        $data[$key . '[' . $key2 . '].' . $key3] = $param3;
                    } else {
                        foreach ($param3 as $key4 => $param4) {
                            if (!is_array($param4)) {
                                $data[$key . '[' . $key2 . '].' . $key3 . '[' . $key4 . '].'] = $param4;
                            } else {
                                foreach ($param4 as $key5 => $param5) {
                                    if (!is_array($param5)) {
                                        $data[$key . '[' . $key2 . '].' . $key3 . '[' . $key4 . '].' . $key5] = $param5;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Artemyev, 2022-04-18
@VjokerA

function arrayCompressor($data, $key = null, &$result = []): array
{
    if (is_array($data)) {
        foreach ($data as $index => $param) {
            if ($key === null) {
                $newKey = $index;
            } else {
                $newKey = $key . '[' . $index . ']';
            }

            arrayCompressor($param, $newKey, $result);
        }
    } else {
        $result[$key] = $data;
    }

    return $result;
}

$array = [
    'RoadServiceAutos' => [
        [
            'RoadServices' => [
                [
                    'CountryAlpha2Code' => 'RU',
                    'CountryBeta2Code' => 'EN',
                ],
            ],
            'Test' => "test",
        ],
    ],
];

print_r(arrayCompressor($array));

I threw a quick solution, I think you can do better, but I'm too lazy

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question