1

Say I have an array like this

$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)
);

How can I remove the first dimensional element if one of its 'post_title' or 'post_id' value is repeated?

Example:

Suppose we know that 'post_title' is '10' in two first dimensional elements.

How can I remove the repeated element from $posts? Thanks.

Marcelo Noronha
  • 807
  • 2
  • 12
  • 26

1 Answers1

1

Create a new array where you will store these post_title values. loop through $posts array and unset any duplicates. Example:

$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]);
    }
}

Now in your $posts array you will have unique post_title values.

machineaddict
  • 3,216
  • 8
  • 37
  • 61