1

这是数组

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,似乎没有任何工作正常。

4

3 回答 3

2

简单的方法:

$result = array();

foreach ($input as $item) {
    if (!array_key_exists($item['artist'], $result)) {
        $result[$item['artist']] = $item;
    }
}
于 2013-02-19T05:29:39.630 回答
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;
   }

}
于 2013-02-19T05:30:33.700 回答
-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);
    ?>
于 2013-02-19T06:37:55.943 回答