以下是示例数组:
Array
(
[0] => Array
(
[action] => move
[para1] => h_1
[para2] => loc_231
[day] => day_1
)
[1] => Array
(
[action] => visit
[para1] => poi_231
[para2] => loc_231
[day] => day_1
)
[2] => Array
(
[action] => visit
[para1] => poi_231
[para2] => loc_231
[day] => day_2
)
)
我想根据键day
的值拆分数组,然后将它们组合在一起。
最终数组应如下所示:
Array
(
Array(
[0] => Array
(
[action] => move
[para1] => h_1
[para2] => loc_231
[day] => day_1
)
[1] => Array
(
[action] => visit
[para1] => poi_231
[para2] => loc_231
[day] => day_1
)
)
Array(
[0] => Array
(
[action] => visit
[para1] => poi_231
[para2] => loc_231
[day] => day_2
)
)
)
除了遍历数组之外,有什么更好的方法?是否有任何PHP功能?
答案 0 :(得分:0)
你可以自己动手
$data = array(array("action"=>"1","day"=>"day_2"),array("action"=>"2","day"=>"day_1"),array("action"=>"3","day"=>"day_1"),array("action"=>"4","day"=>"day_2"),array("action"=>"5","day"=>"day_1"));
print_r($data);
function split_on($array,$field)
{
$ret = array();
foreach($array as $arr)
{
$value_field = $arr[$field];
$ret[$value_field][] = $arr;
}
return array_values($ret);
}
print_r(split_on($data,"day"));
结果:
Array
(
[0] => Array
(
[action] => 1
[day] => day_2
)
[1] => Array
(
[action] => 2
[day] => day_1
)
[2] => Array
(
[action] => 3
[day] => day_1
)
[3] => Array
(
[action] => 4
[day] => day_2
)
[4] => Array
(
[action] => 5
[day] => day_1
)
)
Array
(
[0] => Array
(
[0] => Array
(
[action] => 1
[day] => day_2
)
[1] => Array
(
[action] => 4
[day] => day_2
)
)
[1] => Array
(
[0] => Array
(
[action] => 2
[day] => day_1
)
[1] => Array
(
[action] => 3
[day] => day_1
)
[2] => Array
(
[action] => 5
[day] => day_1
)
)
)