PHP用重复值压平数组



我正在尝试展平一个数组,以便删除重复项并保留唯一值。例如:

$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)
          );

由于数组项中的所有值都是字符串,因此为了方便起见,可以将它们用作数组键的一部分。所以这是一个可能的解决方案:

$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));
}

它确实喜欢方便而不是效率,但它很短。

在实际操作中查看

分三步:

  • 首先通过索引收集信息

  • 然后将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 )
$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
)

使用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
    )
) 

希望会帮助它!

相关内容

  • 没有找到相关文章

最新更新