这是我的多维数组:
Array (
[0] => Array ( [0] => 2015-06-01 [1] => active [2] => 345 )
[1] => Array ( [0] => 2015-06-01 [1] => not_active [2] => 337 )
[2] => Array ( [0] => 2015-06-01 [1] => active [2] => 328 )
[3] => Array ( [0] => 2015-06-02 [1] => not_active [2] => 312 )
[4] => Array ( [0] => 2015-06-02 [1] => active [2] => 338 )
[5] => Array ( [0] => 2015-06-02 [1] => active [2] => 346 )
[6] => Array ( [0] => 2015-06-03 [1] => not_active [2] => 317 )
[7] => Array ( [0] => 2015-06-03 [1] => active [2] => 339 )
[8] => Array ( [0] => 2015-06-04 [1] => active [2] => 340 )
[9] => Array ( [0] => 2015-06-04 [1] => not_active [2] => 318 )
[10] => Array ( [0] => 2015-06-05 [1] => active [2] => 322 )
[11] => Array ( [0] => 2015-06-05 [1] => not_active [2] => 341 )
[12] => Array ( [0] => 2015-06-06 [1] => active [2] => 342 )
[13] => Array ( [0] => 2015-06-06 [1] => active [2] => 325 )
[14] => Array ( [0] => 2015-06-07 [1] => active [2] => 343 )
[15] => Array ( [0] => 2015-06-07 [1] => active [2] => 326 )
)
有7天,但有16条记录。我试图创建一个循环,将记录与相同的日期相结合,有7个记录数组。看起来像这样:
Array (
[0] => Array ( [0] => 2015-06-01 [1] => active [2] => 345 [3] => 2015-06-01 [4] => not_active [5] => 337[6] => 2015-06-01 [7] => active [8] => 328)
[1] => Array ( [0] => 2015-06-02 [1] => not_active [2] => 312 [3] => 2015-06-02 [4] => active [5] => 338 [6] => 2015-06-02 [7] => active [8] => 346)
[2] => Array ( [0] => 2015-06-03 [1] => not_active [2] => 317 [3] => 2015-06-03 [4] => active [5] => 339 )
[3] => Array ( [0] => 2015-06-04 [1] => active [2] => 340 [3] => 2015-06-04 [4] => not_active [5] => 318)
[4] => Array ( [0] => 2015-06-05 [1] => active [2] => 322 [3] => 2015-06-05 [4] => not_active [5] => 341 )
[5] => Array ( [0] => 2015-06-06 [1] => active [2] => 342 [3] => 2015-06-06 [4] => active [5] => 325 )
[6] => Array ( [0] => 2015-06-07 [1] => active [2] => 343 [3] => 2015-06-07 [4] => active [5] => 326)
)
下面使用"dates"作为最终输出数组中的键:
<?php
// Initializing
$arr = [
['2015-06-01', 'active', 345],
['2015-06-01', 'not_active', 337],
['2015-06-01', 'active', 328],
['2015-06-02', 'not_active', 312],
['2015-06-02', 'active', 338],
['2015-06-02', 'active', 346],
['2015-06-03', 'not_active', 317],
['2015-06-03', 'active', 339],
['2015-06-04', 'active', 340],
['2015-06-04', 'not_active', 318],
['2015-06-05', 'active', 322],
['2015-06-05', 'not_active', 341],
['2015-06-06', 'active', 342],
['2015-06-06', 'active', 325],
['2015-06-07', 'active', 343],
['2015-06-07', 'active', 326],
];
// The heart of the code:
$out = array();
foreach($arr as $element) {
foreach($element as $val)
$out[$element[0]][] = $val;
}
// Printing
echo "<pre>";
print_r($out);
echo "</pre>";
?>
但是,如果您希望按顺序索引输出数组的键,那么您也可以使用以下代码段:
$out2 = array();
$i = 0;
foreach($out as $element)
$out2[$i++] = $element;
// Printing
echo "<hr>";
echo "<pre>";
print_r($out2);
echo "</pre>";