我有一个数据数组(数组A的所有值都是string
):
这是数据输入(http://pastebin.com/H8wv9aJU)
$A = Array
0=>(
[0] => "03"//main
[1] => "04"//sub
[2] => "05"
[3] => "07"
[4] => "03" //main
[5] => "04"//sub
[6] => "05"
[7] => "06"
[8] => "07"
[9] => "04"//sub
[10] => "05"
[11] => "06"
[12] => "07"
[13] => "04"//sub
[14] => "05"
[15] => "07"
[16] => "03" //main
[17] => "04"//sub
[18] => "05"
[19] => "06"
[20] => "07"
[21] => "04"//sub
[22] => "05"
[23] => "06"
[24] => "07"
[25] => "04"//sub
[26] => "05"
[27] => "07"
);
预期结果(04和07之间的某些元素可能会丢失):
Array
(
[0] => Array // "03"
(
[0] => "030405 07" //because missing 06 see here 2 space
)
[1] => Array // "03"
(
[0] => "0304050607" //concatenate it all together
[1] => "0304050607"//concatenate it all together
[2] => "030405 07"//because missing 06see here 2 space
)
[2] => Array // "03"
(
[0] => "0304050607" //concatenate it all together
[1] => "0304050607" //concatenate it all together
[2] => "030405 07"//because missing 06, see here 2 space
)
)
我尝试过:
$r = -1;
$organized_array = array();//array expected result.
foreach($A as $key=>$rec) {
if(substr($rec,0,2) == "03") {
// CHANGE 1
$save = $rec;// saved "03" yo put in child too.
++$r;//inc parent => $r became 0
$j = 0; // child
$organized_array[$r][$j] = str_replace(array("\r", "\n"), "",$rec);
}
else {
//I STUCKED HERE FOR GETTING THE EXPECTED RESULT
if (($j % 3) > 0) $rec = str_replace(array("\r", "\n"), "",$rec);
// CHANGE 2
else if ($j && $j % 3 == 0) $rec = str_replace(array("\r", "\n"), "",$save.$rec);
$organized_array[$r][floor($j / 3)] .= str_replace(array("\r", "\n"), "", $rec);
++$j;//increment child
}
}
任何人我有什么不对吗?
答案 0 :(得分:1)
我想这是解决问题的方法......
如果您有这样的数组
$A = array("03", "04", "05", "07", "03", "04", "05", "06", "07", "04", "05",
"06", "07", "04", "05", "07", "03", "04", "05", "06", "07", "04", "05", "06",
"07", "04", "05", "07");
...和预期的输出如下:
array(3) {
[0]=>
array(1) {
[0]=>
string(10) "030405 07"
}
[1]=>
array(3) {
[0]=>
string(10) "0304050607"
[1]=>
string(10) "0304050607"
[2]=>
string(10) "030405 07"
}
[2]=>
array(3) {
[0]=>
string(10) "0304050607"
[1]=>
string(10) "0304050607"
[2]=>
string(10) "030405 07"
}
}
试试这个代码!
$r = -1; $r2 = 0; $last_rec = 2;
$organized_array = array();
foreach ($A as $key => $rec) {
if ($rec == "03") {
// parent
if ($r >= 0) $organized_array[$r][$r2] = str_pad($organized_array[$r][$r2], 10, ' ');
$r++;
$r2 = 0;
$organized_array[$r][$r2] = "03";
}
else {
// children
$this_rec = $rec * 1;
if ($this_rec < $last_rec) {
$organized_array[$r][$r2] = str_pad($organized_array[$r][$r2], 10, ' ');
$r2++;
$organized_array[$r][$r2] = "03";
}
if ($this_rec > ($last_rec + 1)) {
$ec = $this_rec - $last_rec - 1;
$organized_array[$r][$r2] .= str_repeat(" ", $ec);
}
$organized_array[$r][$r2] .= $rec;
}
$last_rec = $rec * 1;
}
var_dump($organized_array);
希望有所帮助!