2013-02-19 110 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); 
    ?>