ArrayCleaner.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. /**
  3. * This file is part of the Klarna Core module
  4. *
  5. * (c) Klarna Bank AB (publ)
  6. *
  7. * For the full copyright and license information, please view the NOTICE
  8. * and LICENSE files that were distributed with this source code.
  9. */
  10. namespace Klarna\Core\Helper;
  11. /**
  12. * Class ArrayCleaner
  13. *
  14. * @package Klarna\Core\Helper
  15. */
  16. class ArrayCleaner
  17. {
  18. /**
  19. * Remove duplicate items from a multidimensional array based on a supplied key
  20. *
  21. * @param array $array
  22. * @param string $key
  23. * @return array
  24. */
  25. public function removeDuplicates(array $array, $key = 'id')
  26. {
  27. /** @noinspection CallableInLoopTerminationConditionInspection */
  28. // The count statement is intentional as the array's size will decrease
  29. for ($parent_index = 0; $parent_index < count($array); $parent_index++) {
  30. $duplicate = null;
  31. /** @noinspection CallableInLoopTerminationConditionInspection */
  32. // The count statement is intentional as the array's size will decrease
  33. for ($child_index = $parent_index + 1; $child_index < count($array); $child_index++) {
  34. if (strcmp($array[$child_index][$key], $array[$parent_index][$key]) === 0) {
  35. $duplicate = $child_index;
  36. break;
  37. }
  38. }
  39. if (null !== $duplicate) {
  40. array_splice($array, $duplicate, 1);
  41. }
  42. }
  43. return $array;
  44. }
  45. }