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

Convert Object To Associative Array In Laravel

我正在调用 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 但没有成功。

非常感谢任何帮助。

假设您的回复是 json 类似本例的回复。

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

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

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

因此:

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

returns:

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

我想这就是你想要的。 在您的情况下,没有查看整个响应 json 但根据您编写的示例,我认为它会像:

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

在 Laravel 中,您可以使用 Laravel 集合辅助函数。下面是这个例子:-

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

我想这会对你有所帮助。