PHP删除数组中重复的日期实例


PHP remove duplicate instances of dates in an array

我尝试了array_unique的各种排列,并在这里搜索了关于从数组中删除重复值的其他通用问题,但我不能完全确定我需要的答案。我有一个传递日期和值的数组,并且每个日期只想查看一次DATE值。

我使用这个谷歌图表,只希望日期标签显示一次为每个日期。我不想把它完全去掉,因为我想把它画在图表上。

那么,传递一个数组的例子:

["June 4",30],["June 4",35],["June 5",46],["June 5",38.33],["June 5",12]  

和我想要的:

["June 4",30],["",35],["June 5",46],["",38.33],["",12] 

想法?

由于您正在使用这些数据馈送到google图表中,因此我假设您确切地知道需要什么输出数据。上面已经有一些更好的方法来组织数据的建议,但这可能不会直接用于谷歌图表。

这个怎么样?

$data = [["June 4",30],["June 4",35],["June 5",46],["June 5",38.33],["June 5",12]];
$found = array();
foreach ($data as $i => $x) {
    if (in_array($x[0], $found)) {
        $data[$i][0] = '';
    } else {
        $found[] = $x[0];
    }
}
print_r($data);

基本上,它只是建立一个已经看到的日期列表。我们循环遍历数据,检查是否看到了日期……如果有,则将其从数据中清除,否则将其保存到列表中,以便下次清除。

这里有一个替代解决方案,它只检查连续的重复日期,而不像第一个解决方案会删除所有的重复日期。这可能更接近您绘制图表所需的内容:

$data = [["June 4",30],["June 4",35],["June 5",46],["June 5",38.33],["June 5",12]];
$last = '';
foreach ($data as $i => $x) {
    if ($x[0] == $last) {
        $data[$i][0] = '';
    } else {
        $last = $x[0];
    }
}
print_r($data);

在这种情况下,我们只是跟踪我们看到的最后一个日期…如果我们的新日期匹配,我们清除它

这是您的问题的一个可能的解决方案,尽管我会建议重建为Patashu &;尼古拉R说。

$untrimmed = [["June 4",30],["June 4",35],["June 5",46],["June 5",38.33],["June 5",12]];
$trimmed = stripDates($untrimmed);
function stripDates($dates) {
    foreach( $dates as $key=>$date ) {
        if ($key>0) {
            if ($date[0] === $dates[$key-1][0]) {
                $dates[$key][0] = "";
            } else if($dates[$key-1][0] === "") {
                for ($i = $key-1; $i > -1; $i--) {
                   if ($date[0] === $dates[$i][0]) $dates[$key][0] = "";
                   if ($dates[$key] != "") break;
                }
            }
        }
    }
    return $dates;
}
// Note: This would require dates to be added chronically
//Output: ["June 4",30],["",35],["June 5",46],["",38.33],["",12]

我建议这样做:

$unconstructed = [["June 4",30],["June 4",35],["June 5",46],["June 5",38.33],["June 5",12]];
$constructed = constructAssoc($unconstructed);
function constructAssoc($dates) {
    $constructed = array();
    foreach( $dates as $index=>$date ) {
        if (!array_key_exists($date[0], $constructed)) {
            $constructed[$date[0]] = array("index"=>$index, "value"=>$date[1]);
        } else {
            array_push($constructed[$date[0], ["index"=>$index,"value"=>$date[1]]);
        }
    }
    return $constructed;
}
//Output: ["June 4"=> [["index"=>0, "value"=>30], ["index"=>1, "value"=>35]], "June 5"=>[["index"=>2, "value"=>46], ["index"=>3, "value"=>38.33], ["index"=>4, "value"=>12]]]

注:如果需要更精确的重建,则在推荐的解决方案中添加了索引。