I
I
IgorRastarov2018-02-23 23:22:19
PHP
IgorRastarov, 2018-02-23 23:22:19

How to remove duplicate values ​​in a 2D array?

Hey!
Tell me, please, such a problem. There is an array

Array
(
[0] => Array
  (
    [ID] => 4887
    [IBLOCK_ID] => 302
    [NAME] => Производитель
    [TEST] => Основное
  )

[1] => Array
  (
    [ID] => 4888
    [IBLOCK_ID] => 302
    [NAME] => Производство
    [TEST] => Основное
  )

[2] => Array
  (
    [ID] => 4889
    [IBLOCK_ID] => 302
    [NAME] => Частота
    [TEST] => Не основные характеристики
  )

)

You see, the value of the TEST key is repeated for the first and second. I need to leave only one.
Array is multidimensional so array_unique cannot be
scripted
$new_arr = array() ;
$result_res = array() ;

foreach ($arr as $key => $value) {
    $new_arr[$key] = $value['TEST'] ;
}

$new_arr = array_unique($new_arr) ;

foreach ($new_arr as $key => $value) {
    $new_arrs[$key] = $arr[$key] ;
}

echo "<pre>";
   print_r($new_arrs);
echo "</pre>";

On output, completely deletes the second array. That is, not only the key => value, but the whole
[1] => Array
  (
    [ID] => 4888
    [IBLOCK_ID] => 302
    [NAME] => Производство
    [TEST] => Основное
  )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Merzley, 2018-02-24
@IgorRastarov

You can do this:

//$arr - изначальный массив

        $arExistsTest = [];
        //здесь используется ссылка (&), чтобы можно было удалять вложенный ключ напрямую
       //т.е. чтобы можно было сделать "unset($value['TEST'])", 
       //а не "unset($arr[$key]['TEST'])"
        foreach ($arr as &$value){
            $currentTestValue = $value['TEST'];
            if (isset($arExistsTest[$currentTestValue]))
                unset($value['TEST']);
            else
                $arExistsTest[$currentTestValue] = true;
        }

        //На данном этапе из массива $arr были удалены 
        //все повторяющиеся значения "TEST",
        //встретившиеся второй раз и далее

A
Andrey, 2018-02-23
@VladimirAndreev

newarr = array();
foreach(arr as item) {
if(!isset(newArr[item.Test]) {
newArr[] = item;
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question