首页 > 解决方案 > 如何重写/重新格式化数组?

问题描述

我正在开发一个 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(平台)等等。

先感谢您 :)

标签: phplaravelcollections

解决方案


从代码来看,您似乎正在为CartItem模型使用 Eloquent API 资源。

如果这是正确的,您不应该使用 json_encode,因为它会将您的对象转换为字符串,但您可以尝试直接调用以下toArray方法CartItemCollection

'items' => (new CartItemCollection($items))->toArray()['Items']

此代码可能需要一些调整,因为您没有发布CartItemCollection's 类代码以及用于生成您现在获得的输出结构的其他相关代码。


推荐阅读