循环并插入另一个没有冗余的数组

时间:2015-02-10 15:27:06

标签: php arrays json

如何跳过在我的情况下插入重复相同的数组项值?我知道有内置函数,如数组唯一,但我的情况是不同的。

下面代码生成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);

3 个答案:

答案 0 :(得分:1)

如果$NumArray是静态的,那就像做:

一样简单
foreach (array_unique($NumArray) as $num)
{
    //same code as before
}

但鉴于事实并非如此,你可以写下:

$SecondArray = ();
foreach ($NumArray as $num)
{
    if (!isset($SecondArray[$num]))
    {//key does not exist (yet)
        $SecondArray[$num] = array('alpa' => $num);
    }
}
echo json_encode(array_values($SecondArray));//remove keys, to ensure a JSON array

see the docs

array_values调用确保生成的JSON字符串是JS数组,而不是对象。例如,如果$num1, 2, 3,则没有 array_values的JSON字符串将如下所示:

{
 1: {alpha: 1},
 2: {alpha: 2},
 3: {alpha: 3}
}

使用调用,它看起来像这样:

[
 {alpha: 1},
 {alpha: 2},
 {alpha: 3}
]

答案 1 :(得分:0)

怎么样:

$NumArray = array('1','2','3','4','5','5','5','5','5','5','5','6','6','7');
$SecondArray = array();
foreach($NumArray as $key => $value){
    if(in_array($value, $NumArray){
         array_push($SecondArray, $value);
    }
}
echo json_encode($SecondArray);

答案 2 :(得分:0)

创建一个新数组,然后循环$NumArray以检查该值是否已存在...如果不存在,则将其添加到新数组中。

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

$newArray = array();
foreach( $NumArray as $val ) {
    if( !in_array( $val, $newArray ) ) {
        $newArray[] = $val;
    }
}
echo '<pre>';
print_r( $newArray );
echo '</pre>';
?>