拆分数组并组织值

时间:2011-06-06 12:16:40

标签: php arrays

我有以下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's answer我得出以下解决方案:

/*
 * 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;
    }

1 个答案:

答案 0 :(得分:2)

在此处观看: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);

无论如何请记住下次你的代码:简单就是美丽(现在不再是lol)

相关问题