我正在尝试展平数组,以便删除重复项并保留唯一值。例如:
$places = array(
array("United Kingdom","London","Camden","1"),
array("United Kingdom","London","Camden","5"),
array("United Kingdom","London","Camden","23"),
array("United Kingdom","London","Camden","71")
);
会变成:
$places = array("United Kingdom","London","Camden","1,5,23,71");
或
$places = array('Country' => 'United Kingdom',
'County' => 'London',
'City' => 'Camden',
'Codes' => array(1,5,23,71)
);
答案 0 :(得分:2)
由于数组项中的所有值都是字符串,因此为方便起见,您可以将它们用作数组键的一部分。所以这是一个可能的解决方案:
$temp = array();
foreach($places as $items) {
$id = array_pop($items);
$key = serialize($items);
$temp[$key][] = $id;
}
$result = array();
foreach($temp as $k => $ids) {
$result[] = array_merge(unserialize($k), array($ids));
}
它确实有利于提高效率,但它很短。
<强> See it in action 强>
答案 1 :(得分:1)
分三步:
首先按索引收集信息
然后使用array_unique
获取唯一值
最后加入三个阵列。
<强>代码强>
$places = array(
array("United Kingdom","London","Camden","1"),
array("United Kingdom","London","Camden","5"),
array("United Kingdom","London","Camden","23"),
array("United Kingdom","London","Camden","71")
);
foreach ($places as $p) {
for ($i=0; $i<count($p); $i++) {
$t[$i][]=$p[$i];
}
}
for ($i=0; $i<count($t); $i++) {
$new[$i]= implode(",", array_unique($t[$i]));
}
$result=array_merge($new);
示例强>
print_r($result);
Array ( [0] => United Kingdom [1] => London [2] => Camden [3] => 1,5,23,71 )
答案 2 :(得分:0)
使用array_unique(),例如:
$places = array(
array("United Kingdom","London","Camden","1"),
array("United Kingdom","London","Camden","5"),
array("United Kingdom","London","Camden","23"),
array("United Kingdom","London","Camden","71")
);
echo "<pre>";
print_r(array_unique($places));
o/p
Array
(
[0] => Array
(
[0] => United Kingdom
[1] => London
[2] => Camden
[3] => 1
)
)
希望能帮助它!
答案 3 :(得分:0)
$places = array(
array("United Kingdom","London","Camden","1"),
array("United Kingdom","London","Camden","5"),
array("United Kingdom","London","Camden","23"),
array("United Kingdom","London","Camden","71")
);
$result = array();
foreach($places as $val){
$result['Country'][$val[0]] = $val[0];
$result['County'][$val[1]] = $val[1];
$result['City'][$val[2]] = $val[2];
$result['Codes'][$val[3]] = $val[3];
}
$final = array();
foreach($result as $key=>$value){
$final[$key] = implode(",",$value);
}
echo "<pre>";
print_r($final);
输出:
Array
(
[Country] => United Kingdom
[County] => London
[City] => Camden
[Codes] => 1,5,23,71
)