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

时间:2018-05-17 13:32:05

标签: javascript php ajax laravel

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

   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中添加了数字索引。如何生成一个没有数字的简单{{key,value},{key,value}}对象?

2 个答案:

答案 0 :(得分:2)

将其更改为:

$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);

答案 1 :(得分:1)

如果您在拥有所有变量时最终定义了数组,则可以使用以下语法:

$stats = [
   'remindersCount => $remindersCount,
   'name' => $Name,
   ....
];

如果必须在使用此语法之前执行此操作:

$stats['remindersCount] = $remindersCount;
$stats['name] = $Name;