1

I have the following array in php:

[0] => Array(
  (
    [post_id] => 492,
    [user_id] => 1
  )
[1] => Array(
  (
    [post_id] => 501,
    [user_id] => 1
  )
[2] => Array(
  (
    [post_id] => 568,
    [user_id] => 13
  )
[3] => Array(
  (
    [post_id] => 897,
    [user_id] => 13
  )

What I want to do, is to delete the ones where the user_id already exists. So the result should look like this:

[0] => Array(
  (
    [post_id] => 492,
    [user_id] => 1
  )
[1] => Array(
  (
    [post_id] => 568,
    [user_id] => 13
  )

I need an array, in which every user_id only exists one time.

array_unique() doesn't work for this example. Any ideas?

Thanks!

Brotzka
  • 2,959
  • 4
  • 35
  • 56
  • use iteration to check it. But why you need it? – Aman Rawat Nov 21 '15 at 08:19
  • 4
    Possible duplicate of [How to remove duplicate values from a multi-dimensional array in PHP](http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php) – kodeart Nov 21 '15 at 09:42
  • I need it to limit my posts. I only need one post per user. – Brotzka Nov 21 '15 at 10:23

2 Answers2

1

You can loop through and find unique values as you go:

$exists = array();
foreach($items as $key => $item) {
    if(!in_array($item['user_id'], $exists)) {
        $exists[] = $item['user_id'];
    } else {
        unset($items[$key]);
    }
}

This will unset any arrays that already exist in the $exists array.

Tristan
  • 3,301
  • 8
  • 22
  • 27
0

Here is the easy function to solve the issue.

 $array = Array();
 $array[] = Array('post_id'=>492 , 'user_id' => '1');
 $array[] = Array('post_id'=>501 , 'user_id' => '1');
 $array[] = Array('post_id'=>568 , 'user_id' => '13');
 $array[] = Array('post_id'=>897 , 'user_id' => '13');


 print_r($array);
 print_r(make_unique_by_key($array,'user_id'));
 function make_unique_by_key($m_arr , $key) {

    $tmp_arr = array();
    foreach ($m_arr as &$item) {
        if (!isset($tmp_arr[$item[$key]])) {
         $tmp_arr[$item[$key]] =& $item;
        }
    }
    $ret_arr = array_values($tmp_arr);
    return $ret_arr;
 }
NIlay Mehta
  • 476
  • 3
  • 7