拆分数组并组织值


Split an array and organize the values

我有以下PHP数组:

$b = array
(
    0 =>"03xxx", //Index of main,  substr(index,0,2)
        1 =>"04xxx",
        2 =>"05xxx",
        //3 =>"06xxx" // missing "06" 
        //4 =>"07xxx",
        6 =>"04xxx",
        7 =>"05xxx",
        8 =>"06xxx",
        //9 =>"07xxx"
    10 =>"08xxx",
    11 =>"03xxx" ,// new index of main
        12 =>"04xxx",
        13 =>"05xxx",
        14 =>"06xxx",
        //15 =>"07xxx" missing "07"
    16 =>"08xxx"
);

我需要将其转换为:

/*the expected result 
Array
(
    [0] => Array
        (
            [0] => 03xxx04xxx05xxx          08xxx, // missing 06 ,07
            [1] => 03xxx04xxx05xxx06xxx     08xxx // missing 07 
        )
    [1] => Array
        (
            [0] => 03xxx04xxx05xxx06xxx     08xxx // missing 07
        )
)
*/

更新:

根据yes123的回答,我得出了以下解决方案:

/*
 * thank to @yes123 
*/
function transform($a){
    $result=array();
    $i=0;
    $j=0;
    $last = 2;
    foreach($a as $k=>$v) {
        if (!isset($result[$i]))
            $result[$i]=array('');

        if ( ++$last != $v[1])
            $result[$i][$j] .=  str_repeat(str_pad(" ",5),($v[1]-$last));
        $result[$i][$j] .= $v;
        $last = $v[1];
        if (substr($v,0,2)=='08') {
            $last=3;
            $j++;
        }
        if ($a[$k+1][1]=='3') {
            $last=2;
            $i++;
            $j=0;
        }
    }
    return $result;
    }

在这里观看直播:http://codepad.org/SWOur3HD版本(0.4)

以下是源代码,以防链接失效:

<?php
$a = array
(
    0 =>"03xxx", //Index of main,  substr(index,0,2)
    1 =>"04xxx",
    //2 =>"05xxx",
    //3 =>"06xxx" // missing "06" 
    4 =>"07xxx",
    5 =>"08xxx",
    6 =>"04xxx",
    7 =>"05xxx",
    8 =>"06xxx",
    //9 =>"07xxx" 
    10 =>"08xxx",
    11 =>"03xxx" ,// new index of main
    12 =>"04xxx",
    13 =>"05xxx",
    14 =>"06xxx",
    //15 =>"07xxx" missing "07"
    16 =>"08xxx"
);

$result=array();
$i=0;
$j=0;
$last = 2;
$main='';
$addMain=false;
foreach($a as $k=>$v) {
  if($v[1]=='3')
    $main=$v;
  if (!isset($result[$i]))
    $result[$i]=array('');
  if ( ++$last != $v[1])
    $result[$i][$j] .=  str_repeat('     ',($v[1]-$last));
  if ($addMain) {
    $result[$i][$j] .= $main;
    $addMain=false;
  }
  $result[$i][$j] .= $v;
  $last = $v[1];
  if ($v[1]=='8') {
    $last=3;
    $j++;
    if ($a[$k+1][1]!='3')
      $addMain=true;
  }
  if ($a[$k+1][1]=='3') {
    $last=2;
    $i++;
    $j=0;
    $addMain=false;
  }
}
print_r($result);

无论如何,下次编码时请记住:Simple is Beautiful(现在不再是lol了)