首页 > 解决方案 > 从 json 中删除不需要的数组

问题描述

我是 Laravel 的新手。我正在使用函数创建一个 json 结构。这是我当前的输出:

{
    "success": "1",
    "data": [
        {
            "category_type_id": 1,
            "category_type": "Study",
            "category_icon": "http://192.168.1.132:8000/images/category/study.svg"
        },
        {
            "category_type_id": 2,
            "category_type": "Sports",
            "category_icon": "http://192.168.1.132:8000/images/category/game.svg"
        },
        {
            "category_type_id": 3,
            "category_type": "Other",
            "category_icon": "http://192.168.1.132:8000/images/category/other.svg"
        }
    ]
}

这是我的控制器代码:

$get_all_category = CategoryType::all();

return response()->json(['success' => '1', 'data' => $get_all_category]);

我想要从数据开始的没有数组的结果请需要解决方案

标签: phpjsonlaravellaravel-5eloquent

解决方案


只需从您的 json 响应中删除其他属性:

$get_all_category = CategoryType::all();
return response()->json($get_all_category);

这将像这样返回您的json:

[ 
    { 
        "category_type_id": 1,
        "category_type": "Study",
        "category_icon": "http://192.168.1.132:8000/images/category/study.svg"
    },
    {
        "category_type_id": 2,
        "category_type": "Sports",
        "category_icon": "http://192.168.1.132:8000/images/category/game.svg" },
    {
        "category_type_id": 3
        "category_type": "Other",
        "category_icon": "http://192.168.1.132:8000/images/category/other.svg"
     }
]

如果你想保持成功属性,你可以这样做,但它只会将你想要摆脱的旧数据属性更改为“0”:

$get_all_category = CategoryType::all();
return response()->json(['success' =>'1', $get_all_category]);

推荐阅读