如何编码对其成员之一进行分组的关联数组?
$my_array = Array(
// customer 1
[0] => Array
(
[customer_id] => 1
[cutomer_item] => 7
)
[1] => Array
(
[customer_id] => 1
[cutomer_item] => 9
)
// customer 2
[2] => Array
(
[customer_id] => 2
[cutomer_item] => 3
)
[3] => Array
(
[customer_id] => 2
[cutomer_item] => 5
)
);
我想要分组(csv)customers_items ,如:
[
// customer 1
{
"customer_id" : "1" // customer id preserved
"cutomer_items" : "7,9" // customer items imploded with a comma
}
,
// customer 2
{
"customer_id" : "2"
"cutomer_items" : "3,5"
}
]
我对这么多数组函数(http://php.net/manual/en/ref.array.php)感到困惑。
答案 0 :(得分:1)
这是一个想法:
<?php
$my_array = array(
array('customer_id' => 1, 'cutomer_item' => 7),
array('customer_id' => 1, 'cutomer_item' => 9),
array('customer_id' => 2, 'cutomer_item' => 3),
array('customer_id' => 2, 'cutomer_item' => 7),
);
sort($my_array);
$customer = '';
$gp_array = array();
$carr = false;
foreach($my_array as $item) {
if ($customer!=$item['customer_id']) {
if ($carr!==false) {
$carr['customer_items'] = implode(',',$carr['customer_items']);
$gp_array[] = $carr;
}
$carr = array('customer_id'=>$item['customer_id'], 'customer_items' => array());
}
$customer = $item['customer_id'];
$carr['customer_items'][] = $item['cutomer_item'];
}
if ($carr!==false) {
$carr['customer_items'] = implode(',',$carr['customer_items']);
$gp_array[] = $carr;
}
$json = json_encode($gp_array);
echo $json
?>
[{ “CUSTOMER_ID”:1, “customer_items”: “7,9”},{ “CUSTOMER_ID”:2 “customer_items”: “3,7”}]
答案 1 :(得分:1)
你可以在mysql查询中使用group_concat函数。如果你是通过mysql获取结果