这是我的阵列:
Array (
[0] => Sos, Ser
[1] => Sos, Ser, Pieczarki
[2] => Sos, Ser, Szynka
[3] => Sos, Ser, Salami
[4] => Sos, Ser, Szynka, Pieczarki
[5] => Sos, Ser, Szynka, Ananas
[6] => Sos, Ser, Salami, Pieczarki
[7] => Sos, Ser, Tunczyk, Cebula
)
我想删除重复项。 array_unique()
不起作用。期望的结果:
$result = array('Sos', 'Ser', 'Pieczarki', 'Szynka', 'Salami', 'Ananas','Tunczyk','Cebula');
答案 0 :(得分:0)
根据您想要的最终数组输出,代码应该是这样的:
<?php
$original = array("Sos, Ser",
"Sos, Ser, Pieczarki",
"Sos, Ser, Szynka",
"Sos, Ser, Salami",
"Sos, Ser, Szynka, Pieczarki",
"Sos, Ser, Szynka, Ananas",
"Sos, Ser, Salami, Pieczarki",
"Sos, Ser, Tunczyk, Cebula",
);
$uniques = array();
// Loop over each original string
foreach ($original as $st) {
// Split at ', ' to extract names from each string
$names = explode(", ", $st);
foreach ($names as $name) {
// Store this name as a key in the uniques array
$uniques[$name] = 1;
}
}
$uniques = array_keys($uniques);
print_r($uniques);
/* Output:
Array
(
[0] => Sos
[1] => Ser
[2] => Pieczarki
[3] => Szynka
[4] => Salami
[5] => Ananas
[6] => Tunczyk
[7] => Cebula
)
*/
答案 1 :(得分:0)
假设您的数组为$array
。
$all_items = [];
foreach ($array as $a1) {
foreach ($a1 as $a2) {
if (!in_array($a2, $all_items)) {
$all_items[] = $a2;
}
}
}
return $all_items;
答案 2 :(得分:0)
创建爆炸值的数组,并array_unique()
:
$result = array();
foreach($array as $value) {
$result = array_merge($result, explode(', ', $value));
}
$result = array_unique($result);
答案 3 :(得分:0)
in_array总是有帮助:
#!/usr/bin/env php
<?php
$aLong = [
'Sos, Ser',
'Sos, Ser, Pieczarki',
'Sos, Ser, Szynka',
'Sos, Ser, Salami',
'Sos, Ser, Szynka, Pieczarki',
'Sos, Ser, Szynka, Ananas',
'Sos, Ser, Salami, Pieczarki',
'Sos, Ser, Tunczyk, Cebula',
];
$aTotal = [];
foreach ($aLong as $sSub) {
foreach (preg_split('/, */', $sSub) as $sWord) {
if (!in_array($sWord, $aTotal)) {
$aTotal[] = $sWord;
}
}
}
print_r($aTotal);