在Laravel中将对象转换为关联数组

时间:2019-03-27 13:34:33

标签: php laravel laravel-collection

我正在调用一个API来接收以下对象响应:

+"284": "Khaki's with Black polo shirt (no logo)"
+"286": "Black pants with Yellow shirt"
+"349": "Black pants with white collared shirt"
+"705": "See "Details" Section for Dress Attire"

我想将此对象转换为关联数组,但遇到了一些麻烦。

这就是我想要的:

[
    0 => ["id" => "284", "name" => "Khaki's with Black polo shirt (no logo)"],
    1 => ["id" => "286", "name" => "Black pants with Yellow shirt"],
    2 => ["id" => "349", "name" => "Black pants with white collared shirt"],
    3 => ["id" => "705", "name" => "See "Details" Section for Dress Attire"]
]

甚至是这样:

[
    "284" => "Khaki's with Black polo shirt (no logo)"
    "286" => "Black pants with Yellow shirt"
    "349" => "Black pants with white collared shirt"
    "705" => "See "Details" Section for Dress Attire"
]

我都可以接受这些

我正在尝试做collect($response->result->attire)->toArray(),但这显然只是给了我一个名字列表:

array:4 [
  0 => "Khaki's with Black polo shirt (no logo)"
  1 => "Black pants with Yellow shirt"
  2 => "Black pants with white collared shirt"
  3 => "See "Details" Section for Dress Attire"
]

我尝试使用mapWithKeys失败。

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

在Laravel中,您可以使用Laravel Collection帮助函数。这是示例:-

$arr = [
    "284" =>  "Khaki's with Black polo shirt (no logo)",
    "286" => "Black pants with Yellow shirt",
    "349" => "Black pants with white collared shirt",
    "705" => "See 'Details' Section for Dress Attire"
];
$collection = collect($arr);
$multiplied = $collection->map(function ($name, $key) {
    return [
        "id" => $key,
        "name" => $name
    ];
});
dd($multiplied->values()->toArray());

我认为这会对您有所帮助。

答案 1 :(得分:0)

假设您的响应是一个json响应,例如此示例。

$response = response()->json(['id' => 'string', 'id2' => 'string2']);
$response->getContent();

像我假设您从API接收到的那样制作一个json字符串:

"{"id":"string", "id2":"string2"}"

,因此:

(array) json_decode($response->getContent());

返回:

[
    "id" => "string",
    "id2" => "string2",
]

我想这就是您想要的。 就您而言,在不查看整个响应json的情况下,但根据您编写的示例,我认为它将是:

(array) json_decode($response->getContent()->result->attire);