PHP:删除重复元素并获取数组中的最新数据

桌面
$arr = [
        [
            "id" => '6230061c0e88d709ca0d7bbc',
            'name' => 'Mobile SamSung',
            'slug' => 'mobile-samsung',
            'createdAt' => '1648006346'

        ],
        [
            "id" => '5d1eff529a426778d4b92383',
            'name' => 'Mobile Iphone',
            'slug' => 'mobile-iphone',
            'createdAt' => '1647314181'
        ],
        [
            "id" => '5d1eff6b9a426778d4b92dc4',
            'name' => 'Mobile SamSung',
            'slug' => 'mobile-samsung',
            'createdAt' => '1647314460'

        ],
        [
            "id" => '5f894011266aea580b028cb0',
            'name' => 'Mobile LG',
            'slug' => 'mobile-lg',
            'createdAt' => '1647314456'

        ]
    ];

我有一个数组,在这个数组中有很多重复的子数组,现在我想删除里面的重复数组,只保留最新的数据createdAt请给我你的意见。谢谢

我想得到一个这样的数组:

$arr = [
            [
                "id" => '6230061c0e88d709ca0d7bbc',
                'name' => 'Mobile SamSung',
                'slug' => 'mobile-samsung',
                'createdAt' => '1648006346'

            ],
            [
                "id" => '5d1eff529a426778d4b92383',
                'name' => 'Mobile Iphone',
                'slug' => 'mobile-iphone',
                'createdAt' => '1647314181'
            ],
            [
                "id" => '5f894011266aea580b028cb0',
                'name' => 'Mobile LG',
                'slug' => 'mobile-lg',
                'createdAt' => '1647314456'

            ]
        ];
米克马库萨

您不应该对您的数据进行一次以上的传递。只需将这些name值用作临时键,然后仅在其createAt值大于存储的值时保留重复行的数据。完成循环后重新索引数组。

代码:(演示

$result = [];
foreach ($arr as $row) {
    if (!isset($result[$row['name']]) || (int)$row['createdAt'] > (int)$result[$row['name']]['createdAt']) {
        $result[$row['name']] = $row;
    }
}
var_export(array_values($result));

输出:

array (
  0 => 
  array (
    'id' => '6230061c0e88d709ca0d7bbc',
    'name' => 'Mobile SamSung',
    'slug' => 'mobile-samsung',
    'createdAt' => '1648006346',
  ),
  1 => 
  array (
    'id' => '5d1eff529a426778d4b92383',
    'name' => 'Mobile Iphone',
    'slug' => 'mobile-iphone',
    'createdAt' => '1647314181',
  ),
  2 => 
  array (
    'id' => '5f894011266aea580b028cb0',
    'name' => 'Mobile LG',
    'slug' => 'mobile-lg',
    'createdAt' => '1647314456',
  ),
)

潜在帮助:

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章