我有一个名为 $ output 的数组。如果我做以下事情......
<?php
print_r($output);
?>
......数组的内容看起来像这样......
Array ( [id] => 116 [the_key] => monday [value] => 0 )
Array ( [id] => 116 [the_key] => tuesday [value] => 1 )
Array ( [id] => 116 [the_key] => wednesday [value] => 0 )
Array ( [id] => 133 [the_key] => monday [value] => 0 )
Array ( [id] => 133 [the_key] => tuesday [value] => 1 )
Array ( [id] => 133 [the_key] => wednesday [value] => 0 )
Array ( [id] => 127 [the_key] => monday [value] => 0 )
Array ( [id] => 127 [the_key] => tuesday [value] => 0 )
Array ( [id] => 127 [the_key] => wednesday [value] => 0 )
...但我想以这样的形式提供内容......
Array ( [id] => 116 [monday] => 0 [tuesday] => 1 [wednesday] => 0)
Array ( [id] => 133 [monday] => 0 [tuesday] => 1 [wednesday] => 0)
Array ( [id] => 127 [monday] => 0 [tuesday] => 0 [wednesday] => 0)
有没有一些方法可以做到这一点而不需要循环一百万次?
答案 0 :(得分:2)
我不知道这是否属于“循环一百万次”,但为什么不尝试按id
对项目进行分组?
$newArray = array();
for($i = 0; $i < sizeof($output); $i++) {
$curr = $output[$i];
$id = $curr["id"];
$day = $curr["the_key"];
$value = $curr["value"];
if(array_key_exists($id, $newArray)) {
$newArray[$id][$day] = $value;
} else {
$newArray[$id] = array($day => $value);
}
}
根据我收集的内容,$newArray
应该符合您的规范。