<?php
$a=[
'0'=>[
'a'=>'1',
'b'=>'1',
'c'=>'1',
],
'1'=>[
'a'=>'1',
'b'=>'2',
'c'=>'2',
],
'2'=>[
'a'=>'3',
'b'=>'3',
'c'=>'3',
],
];
#转化成下面的结构
$res=[
'0'=>[
'a'=>'1',
'c'=>[
'0'=>[
'b'=>1,
'c'=>1,
],
'1'=>[
'b'=>2,
'c'=>2,
],
],
],
'1'=>[
'a'=>'3',
'c'=>[
'0'=>[
'b'=>3,
'c'=>3,
],
],
],
];
1
godog 2020-07-24 11:19:26 +08:00
$a=[
'0'=>[ 'a'=>'1', 'b'=>'1', 'c'=>'1', ], '1'=>[ 'a'=>'1', 'b'=>'2', 'c'=>'2', ], '2'=>[ 'a'=>'3', 'b'=>'3', 'c'=>'3', ], ]; $tmp = []; foreach($a as $record){ $valA = $record['a']; $valB = $record['b']; $valC = $record['c']; //a 的值做 key $tmp[$valA][] = [ 'b' => $valB, 'c' => $valC, ]; } $res = []; foreach($tmp as $key=>$val){ $a = $key; $c = []; foreach($val as $part) { $c[] = $part; } $res[] = [ 'a' => $a, 'c' => $c, ]; } |
2
COKETSANG 2020-07-24 18:36:46 +08:00
$a_values = array_unique(array_column($a, 'a'));
$res = []; foreach ($a_values as $key => $value) { foreach ($a as $k => $v) { if ($v['a'] == $value) { if (!$res[$value]) { $res[$value] = ['a' => $value, 'c' => []]; } $res[$value]['c'][] = ['b' => $v['b'], 'c' => $v['c']]; } } } $res = array_values($res); 下次我还是建议你描述性下你的需求,这是我根据你要的结果猜的 |
3
sunny2580839896 OP @godog #1 谢谢大佬,我先看下
|
4
sunny2580839896 OP @COKETSANG #2 上面是原始数组格式,下面是目标数组
|
5
cbasil 2020-07-28 15:28:41 +08:00
$b = array_unique(array_column($a,'a'));
$list = []; foreach($a as $val){ foreach($b as $i=>$v){ if($val['a'] == $v){ unset($val['a']); if(!$list[$i]){ $list[$i] = [ 'a' => $v, 'c' => [$val] ]; }else{ $list[$i]['c'][] = $val; } } } } echo "<pre>";print_r($list);echo "<pre>"; 跟二楼差不多,都是这种方法 |
6
sunny2580839896 OP @cbasil #5 好的,谢谢大佬的辛苦符出
|