我有一个数组,其中包含来自数据库的数据:
$responses = FormResponses::where('form_id', '>=', $phoneFirstElement->id)->where('form_id', '<=', $phoneLastElement->id)->get();
$responsesArray = $responses->toArray();
然后我的嵌套循环:
foreach ($phone as $key => $value2) // Populate Phone Numbers Horizontally
{
$sheet->cell($start.'9', $value2->phone);
// This will fill the responses for each number
foreach ($metrics as $key => $value)
{
$form_id = $value2->id;
$metrics_id = $value->id;
$neededObjects = array_filter(
$responsesArray,
function ($e) use ($form_id, $metrics_id) {
return $e['form_id'] == $form_id && $e['metrics_id'] == $metrics_id;
}
);
var_dump($neededObjects);
exit;
//$responses = FormResponses::where('form_id', '=', $value2->id)->where('metrics_id', '=', $value->id)->get();
//$sheet->cell($start.$count, $neededObjects[$counter]['response']);
$sheet->cell('C'.$count, $value->question);
$sheet->cell('B'.$count, $value->description);
$sheet->cell('A'.$count, $value->metrics_name);
$counter++;
$count++;
$neededObjects = array();
}
$start++;
$count = 10;
//$counter = 0;
}
我的$responsesArray
是有很多记录的数据,所以我想使用array_filter
提取这些数据以获得我需要的特定数据,并将其存储在中
$neededObjects
然而,当我制作var_dump
时,我会得到类似的东西
array (size=1)
0 =>
array (size=7)
'id' => int 141730
'form_id' => int 4430
'metrics_id' => int 1
'response' => string 'Yes' (length=3)
'remarks' => string '' (length=0)
'created_at' => string '2015-11-23 19:30:07' (length=19)
'updated_at' => string '2015-11-23 19:30:07' (length=19)
然后当中的下一条记录循环时
array (size=1)
1 =>
array (size=7)
'id' => int 141731
'form_id' => int 4430
'metrics_id' => int 2
'response' => string 'Yes' (length=3)
'remarks' => string '' (length=0)
'created_at' => string '2015-11-23 19:30:07' (length=19)
'updated_at' => string '2015-11-23 19:30:07' (length=19)
我不明白为什么它在增加。第一个是0
,然后是1
。是的,因为我在嵌套循环中创建了一个array_filter,但我没有向它添加任何有效值,并且数组筛选器会给我一条数据记录,所以我希望它至少是索引0或类似的格式:
array (size=7)
'id' => int 141731
'form_id' => int 4430
'metrics_id' => int 2
'response' => string 'Yes' (length=3)
'remarks' => string '' (length=0)
'created_at' => string '2015-11-23 19:30:07' (length=19)
'updated_at' => string '2015-11-23 19:30:07' (length=19)
array_filter
返回的任何结果都会保留其旧密钥。如果希望重置密钥,则对结果应用array_values
。
如果只想要一个结果,则对结果调用current()
或array_pop()
以获得第一条记录。
即使array_filter
返回一条记录,它仍将在具有相同关键字的原始数组中。
array_filter根据您的filter函数返回键完好无损的数组元素。因此,键(0、1等)是原始数组中的键。使用array_pop获取数组中唯一的元素。