我可以从mysql生成数组,如果有办法让它变得容易。我得到行,目前我正在渲染,如果有一种方法可以在飞行中生成
3,0.4311 | 3,0.1803 | 4,0.1149 | 4,0.0775 | 5,0.4291 | 5,0.5100 |
考虑这个数组,如何合并它:
Array
(
[0] => Array
(
[channel_id] => 3
[value] => 0.4311
)
[1] => Array
(
[channel_id] => 3
[value] => 0.1803
)
[2] => Array
(
[channel_id] => 4
[value] => 0.1149
)
[3] => Array
(
[channel_id] => 4
[value] => 0.0775
)
...
)
所以看起来像这样:
Array
(
[0] => Array
(
[channel_id] => 3
[value] => 0.4311
[value] => 0.1803
)
[1] => Array
(
[channel_id] => 4
[value] => 0.1149
[value] => 0.0775
)
)
以下是我生成此数组的代码:
while($row = $result->fetch_assoc()) {
$array[] = array('channel_id'=>$row['channel_id'],'value'=>$row['value'] );
}
答案 0 :(得分:0)
好的,这似乎不可能,但这是关闭的我可以得到:
$channels_byid = array();
foreach($array as $v){
@$channel = $channels_byid[$v['channel_id']];
if ($array){
if(!is_array($channel[0])){
unset($channels_byid[$v['channel_id']]);
$channels_byid[$v['channel_id']] = $channel;
}
$channels_byid[$v['channel_id']][] = $v;
} else {
$channels_byid[$v['channel_id']] = $v;
}
}
print_r($channels_byid);
哪个输出:
[3] => Array
(
[0] => Array
(
[channel_id] => 3
[value] => 0.7513
)
[1] => Array
(
[channel_id] => 3
[value] => 0.7234
)
)
[4] => Array
(
[0] => Array
(
[channel_id] => 4
[value] => 0.9798
)
[1] => Array
(
[channel_id] => 4
[value] => 0.7625
)
)
答案 1 :(得分:0)
不完全是你所追求的,但它可能有用。 channel_id
成为顶级键,value
成为新数组的值。
$data[] = array('channel_id' => 3, 'value' => 0.4311);
$data[] = array('channel_id' => 3, 'value' => 0.1803);
$data[] = array('channel_id' => 4, 'value' => 0.1149);
$data[] = array('channel_id' => 4, 'value' => 0.0775);
foreach($data as $k => $v) {
$merge[$v['channel_id']][] = $v['value'];
}
$merge
的结果是:
array(2) {
[3]=> array(2) {
[0]=> float(0.4311)
[1]=> float(0.1803)
}
[4]=> array(2) {
[0]=> float(0.1149)
[1]=> float(0.0775)
}
}