我有一个非常大且变化的二维数组,但结构如下:
"MySetup.exe" /MyVar="Hello world"
我想得到类似于array
0 =>
array
'id' => string '6'
'name' => string 'Adams Clasp'
1 =>
array
'id' => int 185
'name' => string 'Acrylic'
2 =>
array
'id' => string '268'
'name' => string 'Adams Clasp (Splints)'
3 =>
array
'id' => int 11
'name' => string 'Arrow Clasp'
4 =>
array
'id' => int 11
'name' => string 'Arrow Clasp'
5 =>
array
'id' => string '0'
'name' => string 'Labial Bow'
6 =>
array
'id' => string '6'
'name' => string 'Adams Clasp'
7 =>
array
'id' => string '6'
'name' => string 'Adams Clasp'
数组的输出,如果它不是多维/只是键和array_count_values()
,除了保留关联的name
作为价值并保持多维。在此示例中,输出应如下所示:
'id'
正在运行array
'Adams Clasp' =>
array
'id' => string '6'
'count' => int 3
'Acrylic' =>
array
'id' => int 185
'count' => int 1
'Adams Clasp (Splints)' =>
array
'id' => string '268'
'count => int 1
'Arrow Clasp' =>
array
'id' => int 11
'count' => int 2
'Labial Bow' =>
array
'id' => string '0'
'count' => int 1
答案 0 :(得分:1)
正确构造的foreach循环可以解决这个问题。首次找到名称时,将其设置为键,并为其声明默认子阵列(id
和count
= 0
)。然后只需增加每次出现的计数值。
代码:(Demo)
$array=[
['id'=>'6','name'=>'Adams Clasp'],
['id'=>185,'name'=>'Acrylic'],
['id'=>'268','name'=>'Adams Clasp (Splints)'],
['id'=>11,'name'=>'Arrow Clasp'],
['id'=>11,'name'=>'Arrow Clasp'],
['id'=>'0','name'=>'Labial Bow'],
['id'=>'6','name'=>'Adams Clasp'],
['id'=>'6','name'=>'Adams Clasp']
];
foreach($array as $a){
if(!isset($result[$a['name']])){
$result[$a['name']]=['id'=>$a['id'],'count'=>0];
}
++$result[$a['name']]['count'];
}
var_export($result);
输出:
array (
'Adams Clasp' =>
array (
'id' => '6',
'count' => 3,
),
'Acrylic' =>
array (
'id' => 185,
'count' => 1,
),
'Adams Clasp (Splints)' =>
array (
'id' => '268',
'count' => 1,
),
'Arrow Clasp' =>
array (
'id' => 11,
'count' => 2,
),
'Labial Bow' =>
array (
'id' => '0',
'count' => 1,
),
)
答案 1 :(得分:1)
Variant使用数组函数:
$array = [
['id' => '6','name' => 'Adams Clasp'],
['id' => 185,'name' => 'Acrylic'],
['id' => '268','name' => 'Adams Clasp (Splints)'],
['id' => 11,'name' => 'Arrow Clasp'],
['id' => 11,'name' => 'Arrow Clasp'],
['id' => '0','name' => 'Labial Bow'],
['id' => '6','name' => 'Adams Clasp'],
['id' => '6','name' => 'Adams Clasp'],
];
$ids = array_column($array , 'name' , 'id');
array_map(function($count , $id , $name)use(&$out){
$out[$name] = ['id' => $id, 'count' => $count];
} , array_count_values(array_column($array , 'name')) , array_keys($ids),array_values($ids));
print_r($out);