如果重复第二个维度值,则删除第一个维度元素


Removing first dimension element if second dimension value is repeated

>假设我有一个这样的数组

$posts = array(
     array('post_title'=>10, 'post_id'=>1), 
     array('post_title'=>11, 'post_id'=>2),
     array('post_title'=>12, 'post_id'=>3), 
     array('post_title'=>13, 'post_id'=>4),
     array('post_title'=>10, 'post_id'=>5)
);

如果重复第一维元素的"post_title"或"post_id"值之一,如何删除

该元素?

例:

假设我们知道"post_title"在两个一维元素中是"10"。

如何从$posts中删除重复的元素?谢谢。

创建一个新数组,您将在其中存储这些post_title值。 遍历$posts数组并取消设置任何重复项。例:

$posts = array(
     array('post_title'=>10, 'post_id'=>1), 
     array('post_title'=>11, 'post_id'=>2),
     array('post_title'=>12, 'post_id'=>3), 
     array('post_title'=>13, 'post_id'=>4),
     array('post_title'=>10, 'post_id'=>5)
);
$tmp_array = array();
foreach ($posts as $i => $post)
{
    if (!in_array($post['post_title'], $tmp_array)) // if it doesn't exist, store it
    {
        $tmp_array[] = $post['post_title'];
    } else { // element exists, delete it
        unset($posts[$i]);
    }
}

现在,在$posts数组中,您将拥有唯一的post_title值。