You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中PHP array_push生成带数字索引数组,如何返回无索引JSON对象?

如何生成不带数字索引的键值对JSON响应?

我完全懂你的困扰——你现在用array_push把单个键值对的小数组挨个塞进$stats里,结果转成JSON后变成了带数字索引的嵌套结构,前端必须用response[0].remindersCount这种方式访问,太麻烦了。其实只要换个思路构建统计数组就行,根本不用array_push。

问题根源

你每次array_push($stats, array("remindersCount"=>$remindersCount)),本质是把一个只有单个键值的小数组添加到$stats这个索引数组里,最终$stats是一个包含多个小数组的列表,转成JSON自然就变成了带数字键的对象,每个键对应一个独立的小对象。

解决方案:直接构建关联数组

放弃array_push,直接给$stats这个关联数组的键赋值,这样最终的数组本身就是扁平的键值对结构,转成JSON就是你想要的格式。

修改后的控制器代码如下:

public function getStats(Request $request) {
    $now = new DateTime();
    // 初始化一个空的关联数组
    $stats = [];

    // 直接给数组键赋值,替代array_push
    $remindersCount = Reminder::where('created_by', '=', Auth::user()->id )
        ->where('date', '<=', $now)
        ->whereNull('deleted_at')
        ->count();
    $stats['remindersCount'] = $remindersCount;

    // 用户名直接赋值
    $stats['Name'] = Auth::user()->name;

    // 其他统计项也用同样的方式添加
    $stats['favoritesCount'] = ...; // 替换成你的查询逻辑
    $stats['myCallCount'] = ...;
    $stats['totalCalls'] = ...;
    $stats['totalClients'] = ...;
    $stats['sysVersion'] = '1.0';

    // 直接返回关联数组转JSON,不用转成object
    return response()->json($stats);
}

修改后的JSON响应

这样处理后,前端收到的响应会变成扁平的键值对结构:

{"remindersCount":1,"Name":"Ahmed","favoritesCount":1,"myCallCount":13,"totalCalls":13,"totalClients":7,"sysVersion":"1.0"}

前端访问方式

现在你就可以直接通过键名访问对应的值了:

console.log(response.remindersCount); // 输出1
console.log(response.Name); // 输出"Ahmed"

内容的提问来源于stack exchange,提问作者Patriot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:08:43