使用array_chunk php后比较两行

时间:2013-10-24 11:39:21

标签: php arrays match equals


我想比较两列(value,value2)以检查是否相等并将其移动到下一行或元素。这是我的代码。

<?php
  $array = array( 
                         array('value'   =>  10, 'value2' => 1),
                         array('value'   =>  2, 'value2' => 15),
                         array('value'   =>  1, 'value2' => 12),
                         array('value'   =>  3, 'value2' => 13),
                         array('value'   =>  2, 'value2' => 12), //This will move 
                         array('value'   =>  4, 'value2' => 3),
                         array('value'   =>  5, 'value2' => 4),
                         array('value'   =>  5, 'value2' => 5),  //This will move
                         array('value'   =>  3, 'value2' => 4),  //This will move
                         array('value'   =>  4, 'value2' => 5),  //This will move
                         array('value'   =>  10, 'value2' => 5), //Ok reach minimum of 5 count
                         array('value'   =>  9, 'value2' => 3),
                         array('value'   =>  8, 'value2' => 3),
                         array('value'   =>  7, 'value2' => 4),
                         array('value'   =>  7, 'value2' => 8), // This will move
                         array('value'   =>  8, 'value2' => 6), // This will move
                         array('value'   =>  1, 'value2' => 5), //Ok reach minimum of 5 count
                         array('value'   =>  6, 'value2' => 4), 
                         array('value'   =>  6, 'value2' => 3),  // This will move  
                         array('value'   =>  19, 'value2' => 2) //Ok reach minimum of 5 count               
                );

$chunks = array_chunk($array, ceil(count($array)/5));
$array    = array();

for($x = 0, $numX =  count($chunks[0]); $x < $numX; $x++){
    for($y = 0, $numY = count($chunks); $y < $numY; $y++){
        if(isset($chunks[$y][$x]))
        //echo $x.' '.$y.'<br>';
        $array[] = $chunks[$y][$x];
    }
}
print_r($chunks);
?><br>

请随意澄清。

提前致谢。

1 个答案:

答案 0 :(得分:0)

试试这个......

 for($i = 0, $rows = count($array) ; $i < $rows ; $i++){
        for($j = 0 ; $j < $rows -1 ; $j++){
    if($array[$j]['value'] == $array[$j]['value2']){
        ## swap it with next element
        $temp = array();
        $temp = $array[$j];
        $array[$j] = $array[$j + 1];
        $array[$j + 1] = $temp; 
    }
}   
}