循环时跳过数组插入

时间:2015-02-10 14:33:47

标签: php arrays loops

如果最后一个值等于新的值,如何跳过插入数组?下面代码生成12345555555667但我只想要1234567,意味着没有重复的值。

$NumArray = array('1','2','3','4','5','5','5','5','5','5','5','6','6','7');
$SecondArray = array();

foreach($NumArray as $num){
    $SecondArray[] = array(
    'alpa'=>$num
    );
}

echo json_encode($SecondArray);

8 个答案:

答案 0 :(得分:3)

$NumArray = array();

$numArray = array('1','2','3','4','5','5','5','5','5','5','5','6','6','7');

foreach($NumArray as $num){
    if ($previousNumber != $num) {
       echo $num;
       $previousNumber = $num;
    }
}

答案 1 :(得分:1)

使用array_unique()

$NumArray = array();

$NumArray  =array('1','2','3','4','5','5','5','5','5','5','5','6','6','7');
$NumArray = array_unique($NumArray) ;
foreach($NumArray as $num){
echo $num;
}

答案 2 :(得分:0)

您可以使用array_unique获取数组的唯一值,然后迭代它们。

$NumArray = array('1','2','3','4','5','5','5','5','5','5','5','6','6','7');

$unique_arr = array_unique($NumArray) ;

foreach($UniqueArray as $num){
    echo $num;
}

答案 3 :(得分:0)

易:

$NumArray = array('1','2','3','4','5','5','5','5','5','5','5','6','6','7');
$NumArray = array_unique($NumArray);

甚至:

$NumArray = array_unique(array('1','2','3','4','5','5','5','5','5','5','5','6','6','7'));

答案 4 :(得分:0)

这将确保在您首次填充数组时仅添加唯一元素。编辑:

if (!in_array($someNewValue, $NumArray))
{
    $NumArray[] = $someNewValue; 
}

答案 5 :(得分:0)

使用array_unique()

$numArray = array('1','2','3','4','5','5','5','5','5','5','5','6','6','7');
echo json_encode(array_unique($numArray));

答案 6 :(得分:0)

试试这个:

for ($i = 0; $i <count($NumArray); $i++) 
{
  for ($k = $i+1; $k <count($NumArray); $k++) 
  {
    if ($k != $i && $NumArray[$i] == $NumArray[$k]) 
      {
        $NumArray[$k]="";
      }
  }
}

现在数组'NumArray'仅包含原子值。

答案 7 :(得分:-2)

if (end($NumArray) != $someNewValue){
    $NumArray = $someNewValue;
}