我有一个数组数组,每个数组都包含三个参数,如下所示:
Array
(
[0] => Array
(
[title] => 'games'
[transaction_id] => 102
[order_id]=> a
)
[1] => Array
(
[title] => 'media'
[transaction_id] => 95
[order_id]=> b
)
[2] => Array
(
[title] => 'tv'
[transaction_id] => 102
[order_id]=> a
)
[3] => Array
(
[title] => 'jane'
[transaction_id] => 42
[order_id]=> a
)
[4] => Array
(
[title] => 'ads'
[transaction_id] => 95
[order_id]=> b
)
[5] => Array
(
[title] => 'movie'
[transaction_id] => 95
[order_id]=> c
)
)
我想组织数组,以便具有相同transaction_id
值和order_id
的每个数组都位于原始array(Multidimensional)
中的新数组下,如下所示:
Array
(
[0] => Array
(
[0] => games
[1] => tv
)
[1] => Array
(
[0] => jane
)
[2] => Array
(
[0] => ads
[1] => media
)
[3] => Array
(
[0] => movie
)
)
这样做的好方法是什么?
我试过这个:
foreach ($conv_data as $obj) {
if (empty($result[$obj[1]])) {
$result[$obj[1]] = array($obj);
} else {
$result[$obj[1]][] = $obj;
}
}
但这仅聚合在一个参数上。
答案 0 :(得分:2)
使用事务ID和订单ID作为结果数组键来“合并”复制:
$source=/* source array */;
function merge(array $source)
{
$result=array();
foreach($source as $node)
{
$key=$node["transaction_id"]."_".$node["order_id"];
if(!empty($result[$key])) $result[$key][]=$node["title"];
else $result[$key]=array($node["title"]);
}
return array_values($result);
}
print_r(merge($source));
最终结果:
Array
(
[0] => Array
(
[0] => games
[1] => tv
)
[1] => Array
(
[0] => media
[1] => ads
)
[2] => Array
(
[0] => jane
)
[3] => Array
(
[0] => movie
)
)
在返回之前,您可以uksort
根据您的愿望(如果您关心它)。
答案 1 :(得分:1)
$newarray = array();
foreach($arrays as $k=>$v){
$newarray['transaction_id'] = $v['transaction_id'];
$newarray['order_id'] = $v['order_id'];
$newmulti[] = $newarray;
}
echo '<pre>';
print_r($newmulti);
我希望它可以帮到你