将数组的值分组到另一个数组php中

时间:2014-10-07 20:36:29

标签: php arrays foreach

我有一个这样的数组:

$lista = array (
    0 => array ( 'id_dcmnto_rdcdo' => 2, 'dcmnto_rfrnca' => 100 ),
    1 => array ( 'id_dcmnto_rdcdo' => 1 ,'dcmnto_rfrnca' => 104 ),
    2 => array ( 'id_dcmnto_rdcdo' => 1 ,'dcmnto_rfrnca' => 105 ),
    3 => array ( 'id_dcmnto_rdcdo' => 3 ,'dcmnto_rfrnca' => 110 ),
    4 => array ( 'id_dcmnto_rdcdo' => 3 ,'dcmnto_rfrnca' => 111 ),
    5 => array ( 'id_dcmnto_rdcdo' => 3 ,'dcmnto_rfrnca' => 112 ),
    6 => array ( 'id_dcmnto_rdcdo' => 3 ,'dcmnto_rfrnca' => 113 ),
    7 => array ( 'id_dcmnto_rdcdo' => 3 ,'dcmnto_rfrnca' => 120 ),
    8 => array ( 'id_dcmnto_rdcdo' => 3 ,'dcmnto_rfrnca' => 123 ),
    9 => array ( 'id_dcmnto_rdcdo' => 3 ,'dcmnto_rfrnca' => 125 )
);

如何将此数组转换为另一个由dcmnto_rfrnca分组的数组,如下所示:

array(
    [0]=>'100',
    [1]=>'104-105',
    [2]=>'110-113',
    [3]=>'120',
    [4]=>'123',
    [5]=>'125'
);

我有这段代码但是不能正常工作:s

foreach ($lista as $clave => $fila) {


        $rfrnca = $fila['dcmnto_rfrnca'];
        $dcmnto_rfrnca_ms_uno = $fila['dcmnto_rfrnca']+1;
        $dcmnto_rfrnca_prxmo = $lista[$i+1]['dcmnto_rfrnca'];


        if ($dcmnto_rfrnca_prxmo==$dcmnto_rfrnca_ms_uno){
            $ll_consecutivo = true;
        }else{
            $ll_consecutivo = false;
            array_push($cnslddo,$rfrnca);
        }

        echo ' ref anterior anterior '.$rfrnca.' - siguiente ' . $dcmnto_rfrnca_prxmo;
        echo 'masuno ' . $dcmnto_rfrnca_ms_uno . ' - consecutivo '. $ll_consecutivo .' <br>';

        $i++;

echo $fila['dcmnto_rfrnca'] . '<br>'}echo '<br><br><hr>';print_r($cnslddo);

1 个答案:

答案 0 :(得分:0)

第一个:

$a = array();
$t = '';

foreach ($lista as $i => $value) {

    if ($t == '') $t = $value['dcmnto_rfrnca'];
    if (isset($lista[$i+1])) {

        if (((int)$value['dcmnto_rfrnca']+1) == (int)$lista[$i+1]['dcmnto_rfrnca']) {

            $t .= '-'.$lista[$i+1]['dcmnto_rfrnca'];

        }
          else {$a[] = $t; $t = '';}
    } 
      else {$a[] = $t; $t = '';}
}

<强>输出:

Array 
(
    [0] => 100
    [1] => 104-105
    [2] => 110-111-112-113
    [3] => 120
    [4] => 123
    [5] => 125 
)

第二个:

$a = array();
$t = '';

foreach ($lista as $i => $value) {

    if ($t == '') $t = $value['dcmnto_rfrnca'];

    if (isset($lista[$i+1])) {

        if (((int)$value['dcmnto_rfrnca']+1) != (int)$lista[$i+1]['dcmnto_rfrnca']) {

            if ($t != $value['dcmnto_rfrnca']) $t .= '-'.$value['dcmnto_rfrnca']; 
            $a[] = $t; 
            $t = '';

        }

    } 
      else {$a[] = $t; $t = '';}
}

<强>输出:

Array
(
    [0] => 100
    [1] => 104-105
    [2] => 110-113
    [3] => 120
    [4] => 123
    [5] => 125
)