仅基于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,但似乎没有什么效果。

<?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;
   }
}

简单方法:

$result = array();
foreach ($input as $item) {
    if (!array_key_exists($item['artist'], $result)) {
        $result[$item['artist']] = $item;
    }
}
    <?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);
    ?>

相关内容

  • 没有找到相关文章

最新更新