【问题标题】:Json array to json phpjson数组到json php
【发布时间】:2019-03-28 15:21:50
【问题描述】:

我有以下 json。 Retailer_info 属性是 1 个元素的数组。

{
"data": {
    "user": {
        "id": 18626,
        "first_name": "Sip",
        "last_name": "Gemmayzeh",
        "retailer_info": [
            {
                "id": 231,
                "retailer_id": 18626,
                "store_id": 344,
                "created_at": "2018-02-26 09:32:58",
                "updated_at": "2018-02-26 09:32:58"
            }
        ],
        "op_city": {
            "id": 1,
            "ref": "Beirut",
            "currency_id": 5,
            "currency": {
                "id": 5,
                "symbol": "USD"
            }
        },
        "team_lead": null,
        "op_city_languages": [
            {
                "id": 1,
                "locale": "en",
                "name": "English"
            }
        ]
    }
},
"errors": false
}

我想将数组转换为单个 json 对象,如下所示

 "retailer_info": {
                "id": 231,
                "retailer_id": 18626,
                "store_id": 344,
                "created_at": "2018-02-26 09:32:58",
                "updated_at": "2018-02-26 09:32:58"
            },

我的 laravel 代码只是得到这样的模型

$user = User::with('retailerInfo', 'opCity', ...)->get();

我尝试了以下但没有奏效。它使数组保持原样。

$user->retailerInfo = $user->retailerInfo[0];

【问题讨论】:

  • “没用”如何/为什么?
  • 您能否在检索模型后转储$user 值?
  • 我建议创建一个包含您希望(通过 JSON)公开的所有字段的类,然后序列化该类实例。 a) 让您可以控制要公开的内容,并且 b) 有助于让您的行为易于理解。

标签: php arrays json laravel model


【解决方案1】:
$user->retailerInfo = reset($user->retailerInfo);

这应该可以为您解决问题。我遇到了一个类似的问题,我想“取消嵌套”一个数组,这有助于我解决它。

【讨论】:

    【解决方案2】:

    听起来很奇怪,因为->get() 总是返回一个集合 您应该使用->first()->firstOrFail() 仅检索一个元素。 或者您可以调用->each($callback) 对每个元素应用回调。 在 with() 中使用 [] 括号

    $user = User::with(['retailerInfo', 'opCity', ...])->firstOrFail();
    dd($user->retailerInfo->first());
    

    User::with(['retailerInfo', 'opCity', ...])->each(function($user) {
        dump($user->retailerInfo->first());
    });
    

    【讨论】:

      猜你喜欢
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 2011-03-05
      • 2016-05-08
      • 2010-12-04
      • 2012-03-21
      • 1970-01-01
      相关资源
      最近更新 更多