PHP 将原数组中出现的每个值作为新数组的键,对应的原数组的下标作为新数组的值
需 求
[
15 => [
0 => 6
1 => 56
2 => 57
3 => 61
]
16 => [
0 => 6
1 => 92
2 => 93
3 => 99
4 => 106
]
17 => [
0 => 6
1 => 92
2 => 93
3 => 99
]
18 => [
0 => 6
1 => 57
2 => 71
3 => 100
4 => 107
]
19 => [
0 => 6
1 => 66
2 => 115
]
20 => [
0 => 6
1 => 66
2 => 100
]
21 => [
0 => 6
1 => 57
8 => 138
]
22 => [
0 => 6
1 => 57
2 => 118
3 => 126
4 => 138
]
23 => [
0 => 6
1 => 66
22 => 166
]
24 => [
0 => 6
1 => 57
2 => 118
3 => 126
4 => 138
]
25 => [
0 => 6
1 => 66
]
]
改为
[
6=>[
0=>15,
1=>16,
2=>17,
3=>18,
4=>19,
5=>20,
6=>21,
7=>22,
8=>23,
9=>24,
10=>25,
],
56=>[
0=>15
],
57=>[
0=>15,
1=>21,
2=>22,
3=>24,
4=>18,
],
........
]
$arr = [
15 => [0 => 6, 1 => 56, 2 => 57, 3 => 61],
16 => [0 => 6, 1 => 92, 2 => 93, 3 => 99, 4 => 106],
17 => [0 => 6, 1 => 92, 2 => 93, 3 => 99],
18 => [0 => 6, 1 => 57, 2 => 71, 3 => 100, 4 => 107],
19 => [0 => 6, 1 => 66, 2 => 115],
20 => [0 => 6, 1 => 66, 2 => 100],
21 => [0 => 6, 1 => 57, 8 => 138],
22 => [0 => 6, 1 => 57, 2 => 118, 3 => 126, 4 => 138],
23 => [0 => 6, 1 => 66, 22 => 166],
24 => [0 => 6, 1 => 57, 2 => 118, 3 => 126, 4 => 138],
25 => [0 => 6, 1 => 66],
];
$newArr = [];
foreach ($arr as $key => $value) {
foreach ($value as $v) {
if (!array_key_exists($v, $newArr)) {
$newArr[$v] = [$key];
} else {
$newArr[$v][] = $key;
}
}
}
print_r($newArr);
得到结果
[
6=>[
0=>15,
1=>16,
2=>17,
3=>18,
4=>19,
5=>20,
6=>21,
7=>22,
8=>23,
9=>24,
10=>25,
],
56=>[
0=>15
],
57=>[
0=>15,
1=>21,
2=>22,
3=>24,
4=>18,
],
........
]