我知道此问题之前已经被提出过,但似乎没有一个能解决我的问题。
我有一个用户可以拥有多行的数据库。每个的唯一标识符是UID / UUID。没有其他的。其他值可能完全不同。
我执行查询,选择表中的所有行。这将返回一个多维数组:
Array
(
[0] => Array
(
[meta] => 213097312903
[UUID] => 1
[data_name] => wheel_id
[data_value] => 13940
)
[1] => Array
(
[meta] => 2217037902293
[UUID] => 1
[data_name] => car_id
[data_value] => 09278149
)
[2] => Array
(
[meta] => 201207386198
[UUID] => 12
[data_name] => car_id
[data_value] => 639781238
)
)
我想要完成的是处理给定的多维数组并合并相同UUID的所有值,如下所示:
Array
(
[0] => Array
(
[meta] => 213097312903,2217037902293
[UUID] => 1
[data_name] => wheel_id,car_id
[data_value] => 13940,09278149
)
[1] => Array
(
[meta] => 201207386198
[UUID] => 12
[data_name] => car_id
[data_value] => 639781238
)
)
它不完全是这样的,我只是不希望同一用户的数据全部在数组周围。
为了进一步处理,我需要所有用户,所以我不能简单地查询选择所有ID在哪里...
我坚持这个。 :(
答案 0 :(得分:1)
您可以循环该数组并创建一个新数组:
foreach($data as $value)
{
$output[$value['UUID']]['meta'][] = $value['meta'];
$output[$value['UUID']]['data_name'][] = $value['data_name'];
$output[$value['UUID']]['data_value'][] = $value['data_value'];
}
如果要将数组转换为逗号分隔值:
foreach($output as $uuid => $value)
{
$outputWithCSV[$uuid]['meta'] = implode(",",$value['meta']);
$outputWithCSV[$uuid]['data_name'] = implode(",",$value['data_name']);
$outputWithCSV[$uuid]['data_value'] = implode(",",$value['data_value']);
}
$outputWithCSV
将是:
Array
(
[1] => Array
(
[meta] => 213097312903,2217037902293
[data_name] => wheel_id,car_id
[data_value] => 13940,09278149
)
[12] => Array
(
[meta] => 201207386198
[data_name] => car_id
[data_value] => 639781238
)
)
答案 1 :(得分:1)
创建一个基于你的ID的新容器,如果它已经设置,只需连接下一个匹配:
$data = array();
foreach($array as $values) {
if(!isset($data[$values['UUID']])) {
$data[$values['UUID']] = $values;
} else {
$data[$values['UUID']]['meta'] .= ', ' . $values['meta'];
$data[$values['UUID']]['data_name'] .= ', ' . $values['data_name'];
$data[$values['UUID']]['data_value'] .= ', ' . $values['data_value'];
}
}