gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 20:03:10 25 4
gpt4 key购买 nike

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

非常感谢任何帮助。

最佳答案

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

我想这会对你有帮助。

关于php - 在 Laravel 中将对象转换为关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55378527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com