【发布时间】:2015-03-07 22:41:55
【问题描述】:
详情
我想要
- 统计我查询的所有分销商
- 在 JSON 文件中发送它
我知道我总共有89个经销商,我这样做了
dd(count($distributors));我确信最佳实践是什么。
这是我尝试过的
- 我初始化
$count = 0; - 每次循环执行时加 1
$count = $count + 1; - 将结果发送到数组
'count' => $count->toArray()作为我的分销商数组的一部分
这是我的代码
public function index()
{
$distributors = [];
$count = 0;
foreach(
// Specific Distributors
Distributor::where('type','!=','OEM')->where('type','!=','MKP')
->get() as $distributor){
// Variables
$count = $count + 1;
$user = $distributor->user()->first();
$distributors[$distributor->id] = [
'user' => $user->toArray(),
'distributor' => $distributor->toArray(),
'hq_country' => $distributor->country()->first(),
'address' => $distributor->addresses()
->where('type','=','Hq')->first()->toArray(),
'count' => $count->toArray()
];
}
return Response::json($distributors);
}
结果
代码不会运行,因为我的 $distributor 数组不存在...
如果我关闭'count' => $count->toArray(),它将运行。
更新
- 我使用的是 Laravel 4.0
- 代码是我的 UrlController.php 的一部分
【问题讨论】:
-
$count = 0;,$count = $count + 1;,那你试试$count->toArray()?您将整数视为对象。 -
@sjagr:你有什么建议来解决这个问题?你能帮我吗
-
你不能只做
'count' => $count吗?不知道为什么你试图将count变成一个数组,而它只是一个数字。或者(如果你真的想要它作为一个数组)'count => array('count' => $count),但这对我来说似乎是多余的。 -
我不知道。这段代码不是我写的。这取决于您希望
count对您意味着什么。如果您使用聚合计数,请单独使用'count' => $count。如果您想获取查询的计数,请使用'count' => count($distributors),就像您自己说的那样。 -
我不知道,但我很难想象您为什么要在结果中发送结果中所有项目的计数。当您收到回复时,您不能只计算它们吗?例如在javascript中:
data.length
标签: php arrays json laravel laravel-4