1

I have a multidimensional array such as

Array
(
    [0] => Array
        (
            [id] => 1355698
            [comment] => hello
        )

    [1] => Array
        (
            [id] => 1355699
            [comment] => hey
        )

    [2] => Array
        (
            [id] => 1355700
            [comment] => hello
        )

)

The id will always be unique, so the uniqueness of the element will be based on the subarray's value of comment. In this case, array[0] has a duplicate array[2]. (I wonder if there is a better way to phrase this explaination).

array_unique() will not work in this case. Is there an alternative? Thanks!

Aaron W.
  • 9,254
  • 2
  • 34
  • 45
Nyxynyx
  • 61,411
  • 155
  • 482
  • 830
  • I believe this will answer your question: http://stackoverflow.com/questions/2442230/php-getting-unique-values-of-a-multidimensional-array – Mark1inLA May 24 '12 at 02:51
  • Follow Mark1inLA's answer and it leads to http://stackoverflow.com/questions/1861682/php-multi-dimensional-array-remove-duplicate - the accepted answer on that question should do exactly as you ask. – Robbie May 24 '12 at 03:28
  • The accepted answer from http://stackoverflow.com/questions/1861682/php-multi-dimensional-array-remove-duplicate would use the comment as the array key. I don't think its a good solution for the problem, since a comment might have hundreds of characters. – flowfree May 24 '12 at 05:26

2 Answers2

2

Create a new array with id and comment as key=>value pairs, then array_unique().

flowfree
  • 16,356
  • 12
  • 52
  • 76
0
$uniqueArray = array();
foreach ($nonUniqueArray as $i) {
    $uniqueArray[$i['comment']] = $i;
}

// optionally:
// $uniqueArray = array_values($uniqueArray);

var_dump($uniqueArray);
deceze
  • 510,633
  • 85
  • 743
  • 889