我有以下代码:
$keys = array('2', '2', '6', '10', '10', '10', '13', '13', '13', '13', '13', '13', '13', '13', '13', '13', '15', '16', '18', '18', '18', '18', );
$values = array('1712', '1712', '1977', '231', '245', '245', '11', '11', '1121', '1121', '1121', '141', '144', '144', '145', '16', '1980', '153', '153', '171', '171', '183');
$result = array();
foreach ($keys as $i => $k){
$result[$k][] = $values[$i];
}
print_r($result);
哪个输出:
Array (
[2] => Array ([0] => 1712 [1] => 1712 )
[6] => Array ([0] => 1977)
[10] => Array ([0] => 231 [1] => 245 [2] => 245)
[13] => Array ([0] => 11 [1] => 11 [2] => 1121 [3] => 1121 [4] => 1121 [5] => 141 [6] => 144 [7] => 144 [8] => 145 [9] => 16)
[15] => Array ([0] => 1980)
[16] => Array ([0] => 153)
[18] => Array ([0] => 153 [1] => 171 [2] => 171 [3] => 183)
)
我希望"子数组"对每个键都是唯一的,比如下面的输出-(唯一数组):
Array (
[2] => Array ([0] => 1712)
[6] => Array ([0] => 1977)
[10] => Array ([0] => 231 [1] => 245)
[13] => Array ([0] => 11 [1] => 1121 [2] => 141 [3] => 144 [4] => 145 [5] => 16)
[15] => Array ([0] => 1980)
[16] => Array ([0] => 153)
[18] => Array ([0] => 153 [1] => 171 [2] => 183)
)
通过array_map 使用array_unique
$result = array_map('array_unique', $result);
在每个子数组上调用array_unique()函数:
foreach ($result as $key => $subArray) {
$result[$key] = array_unique($subArray);
}
构建子数组后,您需要从子数组中删除重复项,如:
foreach ($result as $ind => $sub_arr)
{
$result[$ind] = array_unique($sub_arr);
}
试试这个:
$keys = array('2', '2', '6', '10', '10', '10', '13', '13', '13', '13', '13', '13', '13', '13', '13', '13', '15', '16', '18', '18', '18', '18' );
$values = array('1712', '1712', '1977', '231', '245', '245', '11', '11', '1121', '1121', '1121', '141', '144', '144', '145', '16', '1980', '153', '153', '171', '171', '183');
$result = array();
foreach ($keys as $i => $k){
$result[$k][] = $values[$i];
}
foreach ($result as $ind => $sub_arr)
{
$result[$ind] = array_unique($sub_arr);
}
print_r($result);
?>
输出:
Array (
[2] => Array ([0] => 1712 [1] => 1712 )
[6] => Array ([0] => 1977)
[10] => Array ([0] => 231 [1] => 245 [2] => 245)
[13] => Array ([0] => 11 [1] => 11 [2] => 1121 [3] => 1121 [4] => 1121 [5] => 141 [6] => 144 [7] => 144 [8] => 145 [9] => 16)
[15] => Array ([0] => 1980)
[16] => Array ([0] => 153)
[18] => Array ([0] => 153 [1] => 171 [2] => 171 [3] => 183)
)