Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP unique array by value?

Tags:

arrays

php

unique

I have an array in PHP that looks like this:

  [0]=>
       array(2) {
           ["name"]=>
              string(9) "My_item"
           ["url"]=>
              string(24) "http://www.my-url.com/"
       }
  [1]=>
     array(2) {
         ["name"]=>
             string(9) "My_item"
         ["url"]=>
            string(24) "http://www.my-url2.com/"
     }

The two values in "name" are the same in this two items. I want to sort out duplicates like this.

How do I create an unique array by checking the "name" value?

like image 791
Jens Törnell Avatar asked Jun 21 '11 08:06

Jens Törnell


Video Answer


1 Answers

basically

$unique_array = [];
foreach($your_array as $element) {
    $hash = $element[field-that-should-be-unique];
    $unique_array[$hash] = $element;
}
$result = array_values($unique_array);
like image 186
user187291 Avatar answered Oct 13 '22 13:10

user187291