如何在foreach循环中删除doubles元素并将日期分配给原始文件?

问题描述 投票:1回答:1

我试图获取的是删除“剩余”字段中的重复值,但是我想在原始字段中分配/保留其日期。元素:

array (size=413)
  0 => 
    array (size=5)
      'Date' => 
        array (size=1)
          0 => int 1588520980
      'Rest' => 123abc
  1 => 
    array (size=5)
      'Date' => 
        array (size=1)
          0 => int 1588520981
      'Rest' => qwe123
  2 => 
    array (size=5)
      'Date' => 
        array (size=1)
          0 => int 1588520983
      'Rest' => qwe123

我尝试了,但是没用

public function find_repeats($arr)
{
    foreach(array_column($arr, 'Rest') as $ckey=>$value) {

        $keys = array_reverse(array_keys(array_column($arr, 'Rest'), $value));

        foreach ($keys as $v) {

            if ($ckey != $v && isset($arr[$v]))
            {
                $arr[$ckey]['Date'][] = $arr[$v]['Date'][0];
                unset($arr[$v]);
            }
        }

    }

    return $arr;
}

这是该表在执行此操作后的外观

array (size=413)
  0 => 
    array (size=5)
      'Date' => 
        array (size=1)
          0 => int 1588520980
      'Rest' => 123abc
  1 => 
    array (size=5)
      'Date' => 
        array (size=1)
          0 => int 1588520981
          1 => int 1588520983
      'Rest' => qwe123

感谢您的帮助! :)

php arrays loops multidimensional-array foreach
1个回答
1
投票

简单的解决方案没有所有这些堆叠的功能:

$newData = [];
foreach ($arr as $item) {
    $rest = $item['Rest'];

    if (!isset($newData[$rest])) {
        $newData[$rest] = $item;
    } else {
        $newData[$rest]['Date'][] = $item['Date'][0];
    }
}
// optionally apply array_values to get 0-indexed array:
$newData = array_values($newData);
© www.soinside.com 2019 - 2024. All rights reserved.