Dipak Dendage
Dipak Dendage

Reputation: 648

How to get string from Flatten a Multidimensional Array with values and keys?

I have following array

    [city] => abc
    [user] => Array
        (
            [0] => Array
                (
                    [id] => 123
                    [name] => xyz
                    [user_address] => Array
                        (
                            [0] => Array
                                (
                                    [address_line_1] => axy
                                    [address_line_2] => 123456
                                )

                            [1] => Array
                                (
                                    [address_line_1] => axy
                                    [address_line_2] => 123456
                                )

                        )

                )

        )

I want string like as follow: city:abc&user.0.id:123&user.0.name:xyz&user.0.user_address.0.address_line_1:axy

I got this type of result for single array: array is

(
    [id] => 123456
    [name] => abc
)

and logic is:

implode('&', array_map(function ($k, $v) {return "$k:$v";}, array_keys($inputsArray), array_values($inputsArray)))

But I'm not able to get multidioamention array to single level.

I refer follwing links but didn't get result

How to Flatten a Multidimensional Array?

How to "flatten" a multi-dimensional array to simple one in PHP?

Please help me out from this.

Thanks.

Upvotes: 2

Views: 357

Answers (1)

deceze
deceze

Reputation: 522442

function flatten_with_paths(array $data, array $path = []) {
    $result = [];

    foreach ($data as $key => $value) {
        $currentPath = array_merge($path, [$key]);
        if (is_array($value)) {
            $result = array_merge($result, flatten_with_paths($value, $currentPath));
        } else {
            $result[join('.', $currentPath)] = $value;
        }
    }

    return $result;
}

$data = [
    'city' => 'abc',
    'user' => [
        [
            'id' => 123,
            'name' => 'xyz',
            'user_address' => [
                [
                    'address_line_1' => 'axy',
                    'address_line_2' => 123456
                ],
                [
                    'address_line_1' => 'axy',
                    'address_line_2' => 123456
                ]
            ]
        ]
    ]
];

echo http_build_query(flatten_with_paths($data));

Upvotes: 1

Related Questions