php - 如何重写/重新格式化数组?
问题描述
我正在开发一个 API,但在将其连接到支付平台时遇到问题,因为他们要求使用以下格式的首选项:
'items' => [
[
'id' => 1,
'title' => 'Product 1',
'description' => 'Some description',
'picture_url' => 'img.png',
'quantity' => 1,
'currency_id' => 'USD',
'unit_price' => 20
],
[
'id' => 2,
'title' => 'Product 2',
'description' => 'Some description',
'picture_url' => 'img.png',
'quantity' => 1,
'currency_id' => 'USD',
'unit_price' => 25
]
]
但我正在从购物车中的商品中收到我的数据,如下所示:
'items' => json_encode(new CartItemCollection($items))
该集合(我的集合 CartItemCollection)具有以下格式:
{
"Items":[
{
"productID":1,
"inventoryID":1,
"name":"Product 1",
"Quantity":1,
"price":20,
"image":"img.png"
},
{
"productID":2,
"inventoryID":1,
"name":"Product2 "
"Quantity":1,
"price":25,
"image":"img.png"
}
],
"items_count":2,
"products_count":2
}
所以我发送(这是错误的):
'items' => "Items":[
{
"productID":1,
"inventoryID":1,
"name":"Product 1",
"Quantity":1,
"price":20,
"image":"img.png"
},
{
"productID":2,
"inventoryID":1,
"name":"Product2 "
"Quantity":1,
"price":25,
"image":"img.png"
}
],
"items_count":2,
"products_count":2
我怎样才能重写或重新格式化:json_encode(new CartItemCollection($items))
以获得正确的数组?
我有点需要这样做:
foreach(项目)在我的收藏中,做:ProductID(我的)重写为 id(平台),数量(我的)重写为数量(平台),价格(我的)重写为 unit_price(平台)等等。
先感谢您 :)
解决方案
从代码来看,您似乎正在为CartItem
模型使用 Eloquent API 资源。
如果这是正确的,您不应该使用 json_encode,因为它会将您的对象转换为字符串,但您可以尝试直接调用以下toArray
方法CartItemCollection
:
'items' => (new CartItemCollection($items))->toArray()['Items']
此代码可能需要一些调整,因为您没有发布CartItemCollection
's 类代码以及用于生成您现在获得的输出结构的其他相关代码。
推荐阅读
- excel - Excel 2013 VBA:复制粘贴公式从复制的单元格中复制值(除了公式)而不是重新计算
- javascript - URL 编码是否足以用于 href 属性以防止 XSS?
- javascript - Mongoose 查询生成器。或未返回预期结果
- c# - 是否需要在数据库中保留刷新令牌
- java - 球衣。带数组的 POJO 返回 415 不受支持的媒体类型
- c# - SqlDataAdapter 返回零行
- ios - 在 Swift 中解压缩 Base64 编码的图像字节
- ruby - 将 Ruby 块中的变量分配给更高的范围
- ruby-on-rails - 输入后Rails覆盖数据库中的值
- docker - 在每次部署中,构建一个包含应用程序的新 docker 映像而不只是更新应用程序有什么优势?