如何使用值和键从Flatten a Multidimensional Array中获取字符串?

时间:2015-03-13 11:02:19

标签: php

我有以下数组

    [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
                                )

                        )

                )

        )

我想要字符串如下: 的城市:ABC&安培; user.0.id:123安培; user.0.name:XYZ&安培; user.0.user_address.0.address_line_1:AXY

我得到了单一数组的这种结果: 数组是

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

和逻辑是:

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

但是我无法将multidioamention数组转换为单一级别。

我引用了以下链接,但没有得到结果

How to Flatten a Multidimensional Array?

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

请帮助我。

感谢。

1 个答案:

答案 0 :(得分:1)

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