A
A
Artem Selyansky2019-11-21 15:09:31
PHP
Artem Selyansky, 2019-11-21 15:09:31

How to remove array with same values ​​in PHP multidimensional array?

$array = array(
  'item-1' => array(
          'a' => 'Повторяющееся значение 1',
          'b' => 'xx1',
          'c' => 'xx2'
  ),
  'item-2' => array(
          'a' => 'Повторяющееся значение 1',
          'b' => 'xx3',
          'c' => 'xx4'
  ),
  'item-3' => array(
          'a' => 'Повторяющееся значение 2',
          'b' => 'xx5',
          'c' => 'xx6'
  ),
  'item-4' => array(
          'a' => 'Повторяющееся значение 2',
          'b' => 'xx7',
          'c' => 'xx8'
  )
);

How to exclude elements in which 'a' is repeated?
You need to get this result:
array(
    'item-1' => array(
        'a' => 'Повторяющееся значение 1',
        'b' => 'xx1',
        'c' => 'xx2'
    )
    'item-3' => array(
        'a' => 'Повторяющееся значение 2',
        'b' => 'xx5',
        'c' => 'xx6'
    )
);

Thanks to all who responded :)

Answer the question

In order to leave comments, you need to log in

4 answer(s)
U
unknown, 2019-11-21
@NikkyNick1

$array = array_map("unserialize", array_unique(array_map("serialize", $array)));

https://ideone.com/0EETQs

F
FanatPHP, 2019-11-21
@FanatPHP

In a loop
Any operations with arrays are done in a loop.

G
green_goo, 2019-11-21
@green_goo

$tmp = [];
foreach ($array as $k => $v) {
  if (array_key_exists($v['a'], $tmp)) {
    unset($array[$k]);
  } else {
    $tmp[$v['a']] = true;
  }
}
var_dump($array);

A
Artem Selyansky, 2019-11-21
@amlvovich

Decided by myself:

foreach(array_reverse($array, true) as $id => $item) {
    if (in_array($item['a'], array_column(array_slice($array, $id+1), 'a'))) {
         unset($array[$id]);
    } 
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question