【问题标题】:Remove a array from an multidimensional array using object value in laravel使用laravel中的对象值从多维数组中删除数组
【发布时间】:2021-05-07 04:13:11
【问题描述】:

我需要从下面的数组中删除重复的数组。

第一个和第三个数组相同,只考虑“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
          ]
    ];

我试图在下面的代码。

-> array_unique($data);

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

预期输出

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

【问题讨论】:

  • 想要回答这个问题的人需要花费大量宝贵的时间。 - “使用对象值”到底是什么意思?试图理解你的意思是猜测。 - 而不是一些奇怪的数组转储,请您进行初始化以获取您的数组。这样,回答的人就有了可以继续工作的东西。 - $all_lambda$all 是什么黑客? - 你到底想用你的“下面的代码”做什么?请在写一个问题时,请考虑它如何为未来的 Stackoverflow 用户提供服务。
  • 您的标准不明确。第二个元素是否保留,因为它有'selected' => true?可以在源头(首先构建此数组的地方)避免这种重复吗?序列化与此有什么关系?

标签: php arrays laravel


【解决方案1】:

array_unique 不起作用,因为您在第三个数组中有 "selected"。我同意 cmets 的观点,这很不清楚,但对我来说,您似乎正在寻找自定义过滤规则,所以一个普通的旧 foreach 是这项工作的工具。

<?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);

【讨论】:

    猜你喜欢
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    相关资源
    最近更新 更多