fork download
  1. <?php
  2.  
  3. // Simple function to remove duplicates by key search in multidimensional array
  4. function keepFirstRemoveDuplicates($array,$key_search)
  5. {
  6.  
  7. $tracking_keywords = array();
  8. $sorted_products = array();
  9.  
  10. foreach ($array as $key => $value) :
  11.  
  12. $key_itself = $value[$key_search]; // = PC or MAC
  13.  
  14. // Check if the key has already been used
  15. if(!in_array($key_itself,$tracking_keywords))
  16. $sorted_products[] = array( 'product' => $value['produkt'], 'type' => $value['type'] );
  17.  
  18. // Insert all used key's to avoid duplicates in a new array
  19. $tracking_keywords[] = $key_itself;
  20.  
  21. endforeach;
  22.  
  23. return $sorted_products; // Returns an array
  24.  
  25. }
  26.  
  27. // The complete product list
  28. $products = [
  29. ['produkt' => 'pc', 'type' => 'laptop1'],
  30. ['produkt' => 'pc', 'type' => 'stasjonær'],
  31. ['produkt' => 'pc', 'type' => 'laptop'],
  32. ['produkt' => 'pc', 'type' => 'screen'],
  33. ['produkt' => 'mac', 'type' => 'laptop1'],
  34. ['produkt' => 'mac', 'type' => 'laptop'],
  35. ['produkt' => 'mac', 'type' => 'screen']
  36. ];
  37.  
  38. // Sorted products
  39. $sorted_products = keepFirstRemoveDuplicates($products,'produkt');
  40.  
  41. // Clean listing output
  42. echo "<pre>";
  43. print_r($sorted_products);
  44. echo "</pre>";
Success #stdin #stdout 0.02s 24400KB
stdin
Standard input is empty
stdout
<pre>Array
(
    [0] => Array
        (
            [product] => pc
            [type] => laptop1
        )

    [1] => Array
        (
            [product] => mac
            [type] => laptop1
        )

)
</pre>