这就是我的数据
array (size=2)
0 =>
array (size=6)
'name' => string 'A new event' (length=11)
'start_time' => string '2015' (length=4)
'end_time' => string '2015' (length=4)
'subscription_start_time' => string '2015' (length=4)
'subscription_end_time' => string '2015' (length=4)
'capacity' => string '5' (length=1)
1 =>
array (size=6)
'name' => string 'A new event 2' (length=13)
'start_time' => string '2015' (length=4)
'end_time' => string '2015' (length=4)
'subscription_start_time' => string '2015' (length=4)
'subscription_end_time' => string '2015' (length=4)
'capacity' => string '5' (length=1)
现在看到两个对象中的start_time
属性..我想用相同的start_time
对所有对象进行分组,所以当我得到像这样的100个对象的数据时,我可以遍历它们并放置所有对象在对象的单个对象数组中使用相同的start_time
...
我知道这将是foreach的简单循环,但是由于我已经处理了对象分组,所以它现在让我感到困惑。有什么帮助吗?
答案 0 :(得分:0)
请尝试以下操作。
function groupBy($array, $key) {
$groupedData = [];
foreach ($array as $value) {
if ( ! array_key_exists($value[$key], $groupedData)) {
$groupedData[$value[$key]] = [];
}
$groupedData[$value[$key]][] = $value;
}
return $groupedData;
}
答案 1 :(得分:0)
这就是我写完的原因 它完美地运作
$all_grouped_events = array_fill(0, sizeof($modelEvent->all_events)-1 , array());
$current_time = $modelEvent->all_events[0]['start_time'];
foreach ($modelEvent->all_events as $event)
{
if($modelEvent->all_events[$count]['start_time'] == $current_time)
{
array_push($all_grouped_events[$curr_count], $event);
$count++;
}
else
{
$curr_count = $count;
$current_time = $modelEvent->all_events[$count]['start_time'];
array_push($all_grouped_events[$curr_count], $event);
$count++;
}
}
代码的第一行非常重要。 array_push
期望一个值应该被推入的数组,所以如果我们创建一个空数组并且在其中推送值它将无法工作,因为我们将访问未定义的索引,因此代码的第一行初始化数组所有索引(静态)并在每个索引处推送一个数组。
这就是所需数据的样子和我想要的内容
array (size=2)
0 =>
array (size=1)
0 =>
array (size=6)
'name' => string 'A new event 3' (length=13)
'start_time' => string '2014' (length=4)
'end_time' => string '2015' (length=4)
'subscription_start_time' => string '2015' (length=4)
'subscription_end_time' => string '2015' (length=4)
'capacity' => string '5' (length=1)
1 =>
array (size=2)
0 =>
array (size=6)
'name' => string 'A new event' (length=11)
'start_time' => string '2015' (length=4)
'end_time' => string '2015' (length=4)
'subscription_start_time' => string '2015' (length=4)
'subscription_end_time' => string '2015' (length=4)
'capacity' => string '5' (length=1)
1 =>
array (size=6)
'name' => string 'A new event 2' (length=13)
'start_time' => string '2015' (length=4)
'end_time' => string '2015' (length=4)
'subscription_start_time' => string '2015' (length=4)
'subscription_end_time' => string '2015' (length=4)
'capacity' => string '5' (length=1)