我需要从数组中删除重复的值。
$original_array
Array
(
[0] => 1 500 2 4 100 51 52
[1] => 515 5 500
[2] => 31 351 5 51 61 71 81 91
[3] => 1 57 101
[4] => 191 25 101 102
)
我以为我能够通过空间爆炸它们来创建一个多维数组,然后使用array_unique()
但这不起作用。
# Create new array
$new_array = array();
# Loop through original_array
foreach($original_array as $original_array_value)
{
$new_array[] = explode(' ', $original_array_value);
}
print_r($new_array);
输出:
Array
(
[0] => Array
(
[0] => 1
[1] => 500
[2] => 2
[3] => 4
[4] => 100
[5] => 51
[6] => 52
)
[1] => Array
(
[0] => 515
[1] => 5
[2] => 500
)
[2] => Array
(
[0] => 31
[1] => 351
[2] => 5
[3] => 51
[4] => 61
[5] => 71
[6] => 81
[7] => 91
)
[3] => Array
(
[0] => 1
[1] => 57
[2] => 101
)
[4] => Array
(
[0] => 191
[1] => 25
[2] => 101
[3] => 102
)
)
只要没有重复的值,最终的数组结果对我来说并不重要。
答案 0 :(得分:2)
你已经到了一半。将其添加到代码的末尾:
$final_array = array();
foreach($new_array as $index => $subarray) {
$final_array = array_merge($final_array, $subarray);
}
$final_array = array_unique($final_array);
然后代码如下:
$original_array = array(
'1 500 2 4 100 51 52',
'515 5 500',
'31 351 5 51 61 71 81 91',
'1 57 101',
'191 25 101 102'
);
# Create new array.
$new_array=array();
# Loop through original_array.
foreach($original_array as $original_array_value)
{
$new_array[]=explode(' ', $original_array_value);
}
$final_array = array();
foreach($new_array as $index => $subarray) {
$final_array = array_merge($final_array, $subarray);
}
$final_array = array_unique($final_array);
echo "<pre>";
print_r($final_array);
echo "</pre>";
更好:合并步骤,如下:
$original_array = array(
'1 500 2 4 100 51 52',
'515 5 500',
'31 351 5 51 61 71 81 91',
'1 57 101',
'191 25 101 102'
);
# Create new array.
$final_array =array();
# Loop through original_array and do the merge at the same time.
foreach($original_array as $original_array_value)
{
$final_array = array_merge($final_array, explode(' ', $original_array_value) );
}
$final_array = array_unique($final_array);
echo "<pre>";
print_r($final_array);
echo "</pre>";
答案 1 :(得分:2)
怎么样:
$arr = array(
0 => '1 500 2 4 100 51 52',
1 => '515 5 500',
2 => '31 351 5 51 61 71 81 91',
3 => '1 57 101',
4 => '191 25 101 102',
);
$imp = trim(implode(' ',$arr));
$exp = array_unique(explode(' ', $imp));
var_dump($exp);
<强>输出强>
Array
(
[0] => 1
[1] => 500
[2] => 2
[3] => 4
[4] => 100
[5] => 51
[6] => 52
[7] => 515
[8] => 5
[10] => 31
[11] => 351
[14] => 61
[15] => 71
[16] => 81
[17] => 91
[19] => 57
[20] => 101
[21] => 191
[22] => 25
[24] => 102
)
答案 2 :(得分:1)
您可以立即构建一个独特的阵列,而不是使用array_unique()
:
$arr = array(
0 => '1 500 2 4 100 51 52',
1 => '515 5 500',
2 => '31 351 5 51 61 71 81 91',
3 => '1 57 101',
4 => '191 25 101 102',
);
$result = array();
foreach ($arr as $item) {
$result += array_flip(explode(' ', $item));
}
+
运算符如果相应的键尚不存在,则会向该数组添加新值。最后,您可以通过观察数组键找到答案:
print_r(array_keys($result));