2013-02-19 75 views
1

这是数组删除重复只有PHP

Array 
(
    [0] => Array 
     (
      [artist] => John Keys 
      [postID] => 254 
     ) 

    [1] => Array 
     (
      [artist] => Jay Bloom 
      [postID] => 249 
     ) 

    [2] => Array 
     (
      [artist] => John Keys 
      [postID] => 216 
     ) 

    [3] => Array 
     (
      [artist] => Angie Belle 
      [postID] => 225 
     ) 
) 

,我想只从艺术家的元素删除所有副本。请注意,0和2具有相同的艺术家,但具有不同的postID。我只想保留艺术家的第一次出现,并删除所有其他人。所以,结果我想有是

Array 
(
    [0] => Array 
     (
      [artist] => John Keys 
      [postID] => 254 
     ) 

    [1] => Array 
     (
      [artist] => Jay Bloom 
      [postID] => 249 
     ) 
    [2] => Array 
     (
      [artist] => Angie Belle 
      [postID] => 225 
     ) 
) 

我试过array_unique也序列化和做一个array_map,似乎没有任何工作的权利。

回答

2
<?php 
$array = Array 
(
    '0' => Array 
     (
      'artist' => 'John Keys', 
      'postID' => 254 
     ), 

    '1' => Array 
     (
      'artist' => 'Jay Bloom', 
      'postID' => 249 
     ), 

    '2' => Array 
     (
      'artist' => 'John Keys', 
      'postID' => 216 
     ), 

    '3' => Array 
     (
      'artist' => 'Angie Belle', 
      'postID' => 225 
     ) 
); 
$newarray = array(); 
foreach($array as $key => $val){ 
    if(!array_key_exists('artist', $newarray)){ 
    $newarray[$val['artist']] = $val; 
    } 
} 
echo '<pre>'; 
print_r($newarray); 

编辑:使用数字键:

$newarray = array(); 
$temp = array(); 

foreach($array as $key => $val){ 

    if(!in_array($val['artist'], $temp)){ 
    $temp[] = $val['artist']; 
    } 
    if(!array_key_exists(array_search($val['artist'], $temp), $newarray)){ 
    $newarray[array_search($val['artist'], $temp)] = $val; 
    } 

} 
+0

感谢阿卡姆!这很好,我唯一的问题是标识符变成[artistname] => postID – 2013-02-19 07:15:40

+0

是的,使用像这样通过艺术家名称访问它,我可以将它改为数字:) – 2013-02-19 07:17:09

2

简单的方法:

$result = array(); 

foreach ($input as $item) { 
    if (!array_key_exists($item['artist'], $result)) { 
     $result[$item['artist']] = $item; 
    } 
} 
-1
<?php 
    $a=array(
     "0" => array 
      (
       "artist" => "John Keys", 
       "postID" => "254" 
      ), 

     "1" => array 
      (
       "artist" => "Jay Bloom", 
       "postID" => "249" 
      ), 

     "2" => array 
      (
       "artist" => "John Keys", 
       "postID" => "216" 
      ), 

     "3" => array 
      (
       "artist" => "Angie Belle", 
       "postID" => "225" 
      ) 
     ); 



    var_dump($a); 

    for($i=0;$i<count($a);$i++) 
    { 
for($j=$i+1;$j<count($a); $j++) 
{ 

    $tmp1=$a[$i]["artist"]; 
    $tmp2=$a[$j]["artist"]; 

    if($tmp1==$tmp2) 
    { 

     unset($a[$j]); 

    } 
    $tmp3=array_values($a); 

    $a=$tmp3; 
    } 


     } 

    var_dump($a); 
    ?>