gpt4 book ai didi

javascript - Laravel - PHP array_push 为 Ajax 生成编号索引

转载 作者:行者123 更新时间:2023-11-28 17:31:12 25 4
gpt4 key购买 nike

我有一个 ajax 请求,它将更新页面上的某些统计信息。我的ajax Controller 是这样的:

   public function getStats (Request $request) {

$now = new DateTime();
$stats = [];

$remindersCount = Reminder::where('created_by', '=', Auth::user()->id )
->where('date', '<=', $now)
->whereNull('deleted_at')
->count();

array_push($stats,array("remindersCount"=>$remindersCount));

$Name= Auth::user()->name;

array_push($stats,array("Name"=>$Name));

.... more queries and array_push ...

return response()->json((object) $stats);

javascript收到的响应是:

{"0":{"remindersCount":1},"1":{"Name":"Ahmed"},"2":{"favoritesCount":1},
"3":{"myCallCount":13},"4":{"totalCalls":13},"5":{"totalClients":7},
"6":{"sysVersion":"1.0"}}

因此,在 Javascript 中,我无法使用 reponse.remindersCount 来访问其值,我必须使用 response[0].remindersCount

我知道原因是 array_push 在 php.ini 中添加了数字索引。如何生成一个没有数字的简单 {{key,value},{key,value}} 对象?

最佳答案

将其更改为:

$now = new DateTime();
$stats = [];

$remindersCount = Reminder::where('created_by', '=', Auth::user()->id )
->where('date', '<=', $now)
->whereNull('deleted_at')
->count();

$stats['remindersCount'] = $remindersCount;
$stats['name'] = Auth::user()->name;

.... more queries ...

return response()->json($stats);

关于javascript - Laravel - PHP array_push 为 Ajax 生成编号索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50392791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com