PHP:重复的值去除 [英] PHP: duplicate value removal

查看:95
本文介绍了PHP:重复的值去除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2阵列,例如1000键的各自之一成立的温度值,而另一个小时

示例阵列温度:

  [0] = 3.1
[1] = 4.3
[2] = 4.1
[3] = 5.1
[4] = 4.1

举例小时数组:

  [0] = 0
[1] = 1
[2] = 2
[3] = 3
[4] = 3

这样做的问题是,当我结合这些到阵列和绘制这例如pchart我有在X的值太多,它被混乱。结果
所以我需要删除重复小时,并用NULL再更换,这样不需要的时间不在x轴上。结果
我想保持在第一个小时在数组中,第二到重复的端部可被设置为空

时针输出数组应该是:

  [0] = 0
[1] = 1
[2] = 2
[3] = 3
[4] = NULL
等等


解决方案

您数组进行排序,所以......这个怎么样?

  $小时=阵列(0,1,2,3,3,4,4,5);
$preV = -1;
的foreach($小时,&安培; $小时){
  如果($$ p $光伏=== $小时){
    $小时= NULL;
  }
  其他{
    $preV = $小时;
  }
}
未设置($小时);
的print_r($小时); // 0,1,2,3,NULL,4,NULL,5 ...

I have 2 arrays with for example 1000 key's each, one holds a temperature value and the other the hour.

Example array temp:

[0] = 3.1
[1] = 4.3
[2] = 4.1
[3] = 5.1
[4] = 4.1

Example hour array:

[0] = 0
[1] = 1
[2] = 2
[3] = 3
[4] = 3

The problem with this is that when i combine these to arrays and plot this in for example pchart i have too many values on the X and it gets cluttered.
So what i need to to remove the duplicate hours and replace then with "NULL", so that the unneeded hours are not plotted on the x axis.
I want to keep the first hour in the array, the second to the end of the duplicates can be set to "NULL"

The hour output array should be:

[0] = 0
[1] = 1
[2] = 2
[3] = 3
[4] = NULL
etc.

解决方案

Your array is sorted, so... how about this?

$hours = array(0,1,2,3,3,4,4,5);
$prev = -1;
foreach ($hours as &$hour) {
  if ($prev === $hour) {
    $hour = NULL;
  }
  else {
    $prev = $hour;
  }
}
unset($hour);
print_r($hours); // 0,1,2,3,NULL,4,NULL,5...

这篇关于PHP:重复的值去除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆