PHP二维数组修改指定的重复字段

$list=array(
    array(
        'orderid'=>0,
        'name'=>'A'
    ),
    array(
        'orderid'=>0,
        'name'=>'B'
    ),
    array(
        'orderid'=>0,
        'name'=>'C'
    )
);
$result=repeat($a,'orderid');
print_r($list);

//处理数组,重复的字段自动加1
function repeat($array,$key){
    foreach($array as $k1 => $v1){  // 0 0 0 0
        $new_array=$array;
        foreach($new_array as $k2 => $v2){ // 0 0 0 0
            if($k1!=$k2){ //防止自己和自己比
                if($array[$k1][$key] == $new_array[$k2][$key]){ //发现重复
                    $array[$k1][$key]=$array[$k1][$key]+1;
                    $array=repeat($array,$key); //递归
                }
            }
        }
    }
    return $array;
}

运行结果:
Array ( [0] => Array ( [orderid] => 2 [name] => A ) [1] => Array ( [orderid] => 1 [name] => B ) [2] => Array ( [orderid] => 0 [name] => C ) )

你可能感兴趣的:(PHP)