PHP从Array中删除除具有相同属性的所有对象外的所有对象

时间:2019-06-26 00:25:56

标签: php laravel eloquent

使用雄辩,我想用'Title'B从$ outputs数组中删除2个对象,并且只保留一个。

$ outputs具有以下信息:

[
    {
        "Title": "A",
        "Publication date": "2013",
    },
    {
        "Title": "B",
        "Publication date": "2010",
    },
    {
        "Title": "B",
        "Publication date": "2999",
    },
    {
        "Title": "B",
        "Publication date": "5555",
    },
];

我知道有很多关于此的文章,但我自己找不到办法。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

如果这是用于数组/集合,而不是用于Eloquent查询,则可以使用集合keyBy方法来获取唯一值。

https://laravel.com/docs/5.8/collections#method-keyby

$data = [
    [
        "Title" => "A",
        "Publication date" => "2013",
    ],
    [
        "Title" => "B",
        "Publication date" => "2010",
    ],
    [
        "Title" => "B",
        "Publication date" => "2999",
    ],
    [
        "Title" => "B",
        "Publication date" => "5555",
    ],
];

$collection = collect($data)->keyBy('Title');

然后您的输出将如下所示:

Collection {#1389 
  #items: array:2 [
    "A" => array:2 [
      "Title" => "A"
      "Publication date" => "2013"
    ]
    "B" => array:2 [
      "Title" => "B"
      "Publication date" => "5555"
    ]
  ]
}

keyBy方法将为您提供每个标题的集合中的最后一项,因此,如果您要获取特定项目,可以在调用keyBy之前对集合进行排序:

// get each Title with the highest Publication date
$collection = collect($data)->sortBy('Publication date')->keyBy('Title');

// get each Title with the lowest Publication date
$collection = collect($data)->sortByDesc('Publication date')->keyBy('Title');

如果要返回不包含键“ A”和“ B”的数组,则可以执行以下操作:

$collection = collect($data)->keyBy('Title')->values()->toArray();

输出:

array:2 [
  0 => array:2 [
    "Title" => "A"
    "Publication date" => "2013"
  ]
  1 => array:2 [
    "Title" => "B"
    "Publication date" => "5555"
  ]
]

答案 1 :(得分:0)

您可以通过在查询中使用destinctgroupBy来做到这一点。