当多维数组中存在重复时,数组移动

时间:2013-10-21 14:50:30

标签: php arrays multidimensional-array


我有这个代码。=在php中有新手经验

$values   =  array(
                   array('field'   =>  1),
                   array('field'   =>  2),
                   array('field'   =>  2),
                   array('field'   =>  3),
                   array('field'   =>  4),
                   array('field'   =>  4),
                   );

print_r($values);
foreach($values as $k => $v) { 
      //Check for duplicate
      //Move the value "field" to another part of the array which has no equal value on range of index 2 

}

>
如果代码在2个索引中找到重复项,则移动数组直到达到无重复的代码。

我的预期结果将是:可以是满足给定传导的不同结果。

 1.   Array(
                [0] => Array('field'   =>  4),
                       Array('field'   =>  2),
                       Array('field'   =>  1),
                       Array('field'   =>  4),
                       Array('field'   =>  3),
                       Array('field'   =>  2)
                       );
 2.   Array(
                [0] => Array('field'   =>  2),
                       Array('field'   =>  1),
                       Array('field'   =>  4),
                       Array('field'   =>  3),
                       Array('field'   =>  2),
                       Array('field'   =>  4)
                       );


我想使用array_splice和array_unique,但不知道如何开始。也许它是一个循环而不是foreach。找到一个副本并移动该值,如果发现重复,索引为2.请帮助我。

1 个答案:

答案 0 :(得分:1)

试试sorting array functions。这可以做到这一点,并不完美,但是开始是个好点:

<?php
$values   =  array(
  array('field'   =>  1),
  array('field'   =>  1),
  array('field'   =>  2),
  array('field'   =>  2),
  array('field'   =>  2),
  array('field'   =>  3),
  array('field'   =>  3),
  array('field'   =>  4),
  array('field'   =>  4),
);

print_r($values);
uksort($values, create_function('$x,$y','return ($y === $x) ? -1 : 1;'));
print_r($values);
?>

我不知道你的价值观多么多样,祝你好运。