简体   繁体   中英

Remove a array from an multidimensional array using object value in laravel

i need to remove duplicate array from below array.

first and third arrays are same, consider only "id"

$data = [
          [
              'id' => 'test_fun%test',
              'text' => 'test_fun',
              'data-value' => 'test',
          ],
          [
              'id' => 'test_fun1%test',
              'text' => 'test_fun1',
              'data-value' => 'test',
          ],
          [
              'id' => 'test_fun%test',
              'text' => 'test_fun',
              'data-value' => 'test',
              'selected' => true
          ]
    ];

i'm tried to below code.

-> array_unique($data);

-> array_map("unserialize", array_unique(array_map("serialize", $data)));

Expected Output

  $data = [
          
          [
              'id' => 'test_fun1%test',
              'text' => 'test_fun1',
              'data-value' => 'test',
          ],
          [
              'id' => 'test_fun%test',
              'text' => 'test_fun',
              'data-value' => 'test',
              'selected' => true
          ]
    ];

array_unique is not going to work since you have "selected" in the third array. I agree with the comments that this is quite unclear but to me it seems you're looking for a custom filtration rule, so a plain old foreach is the tool for the job.

<?php

$data = [
    [
        'id' => 'test_fun%test',
        'text' => 'test_fun',
        'data-value' => 'test',
    ],
    [
        'id' => 'test_fun1%test',
        'text' => 'test_fun1',
        'data-value' => 'test',
    ],
    [
        'id' => 'test_fun%test',
        'text' => 'test_fun',
        'data-value' => 'test',
        'selected' => true
    ]
];

$filtered = [];
foreach ($data as $row) {
    $id = $row['id'];
    $selected = $row['selected'] ?? false;

    if (isset($filtered[$id])) {
        if (!$selected) {
            continue;
        }
        unset($filtered[$id]);
    }

    $filtered[$id] = $row;
}

// optional use if you don't want ids for keys
$filtered = array_values($filtered);


print_r($filtered);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM