Laravel 5.4:返回响应json组

时间:2019-02-18 15:00:15

标签: php arrays json laravel-5.4

我有这个控制器,它按日期对Collection进行分组

public function index() {
        $poLists = ( new PurchaseOrder() )
            ->where( 'needed_quantity', '>', 0 )
            ->where( 'supplier_id', $this->guard()->user()->id )
            ->get()->groupBy( function ( $item ) {
                return [ $item->created_at->format( 'Y-m-d HH:mm:ss' ) ];
            } );

        return response()->json( $poLists, 200 );
    }

工作正常,这是输出

{
    "2019-02-18 1212:0202:3939": [
        {
            "id": 2,
            "created_at": "2019-02-18 12:16:39",
            "updated_at": "2019-02-18 12:16:39"
        }
    ],
    "2019-02-18 1515:0202:0202": [
        {
            "id": 4,
            "created_at": "2019-02-18 15:21:02",
            "updated_at": "2019-02-18 15:21:02"
        },
        {
            "id": 5,
            "created_at": "2019-02-18 15:21:02",
            "updated_at": "2019-02-18 15:21:02"
        }
    ],

有没有一种方法可以为每个组添加静态密钥,如

{
    date: "2019-02-18 1212:0202:3939" [
        {
            "id": 2,
            "created_at": "2019-02-18 12:16:39",
            "updated_at": "2019-02-18 12:16:39"
        }
    ],
    date: "2019-02-18 1515:0202:0202": [
        {
            "id": 3,
            "barcode": 33254,
            "status": 0,
            "created_at": "2019-02-18 15:21:02",
            "updated_at": "2019-02-18 15:21:02"
        },
        {
            "id": 5,
            "created_at": "2019-02-18 15:21:02",
            "updated_at": "2019-02-18 15:21:02"
        }
    ],

这里是date是静态密钥

1 个答案:

答案 0 :(得分:0)

用所需关键字的数组包装$poList结果数据:

$results = [
    'date' => $poLists
];
return response()->json($results, 200);

现在,在$results['date']中,所有数据均按日期分组:

{
    "date": [
        "2019-02-18 1212:0202:3939" [
            {
               "id": 2,
                "created_at": "2019-02-18 12:16:39",
                "updated_at": "2019-02-18 12:16:39"
            }
        ],
        "2019-02-18 1515:0202:0202": [
            {
                "id": 3,
                "barcode": 33254,
                "status": 0,
                "created_at": "2019-02-18 15:21:02",
                "updated_at": "2019-02-18 15:21:02"
            },
            {
                "id": 5,
                "created_at": "2019-02-18 15:21:02",
                "updated_at": "2019-02-18 15:21:02"
            }
        ]
    ]
}

这是您要寻找的吗?