如何在php中从字符串格式化数组?

时间:2016-09-07 14:32:51

标签: php arrays

我想如果字符串中的第一个数字是2,则输出将是2个数组。如何从字符串中作为每个数组爆炸。

我的代码

<?php

$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00;";


$data = explode(',',$str); 
$out = array();
for($i=1;$i < count($data)-1;$i++){

   $out[]= explode(';',$data[$i]);

}

$i = $out[0][0];


foreach ($out as $key => $value) {


for($a=0;$a < $i; $a++){

    echo $value[$a]. "<br/>";
}

}

?>

我得到的结果 221107-09-201607-09-201608-09-201610-09-201613 但我想要这种格式

<?php

$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00;";

//format will be split by semicomma ;
$arr1 = Array('2','1','07-09-2016','08-09-2016','1','100.00');
$arr2 = Array('2','1','07-09-2016','10-09-2016','3','450.00');

?>

2 个答案:

答案 0 :(得分:2)

php函数array_column将在这里派上用场。这是一个简短的代码示例,应该输出您要查找的内容。

<?php
//Your original input
$str =     "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00";

//explode the array into its sub-arrays
$arrs = explode(",", $str);

//remove the first element that sets how many elements are in each array
$numArrs = array_shift($arrs);

//convert strings into those wanted sub-arrays
array_walk($arrs, function(&$val, $key) {  $val = explode(';',$val); });

//make the answer we need
$ans = array();
for($i=0; $i<$numArrs; $i++) {
    //array_column does all the work that we want, making life easy
    $ans[] = array_column($arrs, $i);
}

var_dump($ans);

这个过程确实假设字符串的格式正确我们正在寻找的东西 - 如果不是这样的话,它会失败。

答案 1 :(得分:1)

使用explode()功能!真的很酷 这是我如何解决这个问题。你最终会得到一个包含我代码的二维数组。您可以使用$arr1访问$fourthStep[0],使用$fourthStep[1]等访问$ arr2 ...

<?php
 $str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00;";
 $fourthStep = array();

 //First, let's split that string up into something a little more.. readable.
 $firstStep = explode(",",$str);
 //$firstStep[0] contains our count for the total array count.
 foreach($firstStep as $secondStep){ //Our second step is to loop through the newly created array which splits each section of your array
     if ($secondStep != $firstStep[0]){ //skip the first part, as that is only telling us of array count
         $thirdStep = explode(";",$secondStep); //third step is to get each data part of each section. The count of this array should be 'firstStep[0]-1'       
         for($i = 0; $i<$firstStep[0]; $i++){
             //Now we want to assign the values into a 2D array
            $fourthStep[$i][count($fourthStep[$i])] = $thirdStep[$i];
         }


     }
 }

 var_dump($fourthStep);
 ?>

结果:
array(2) { [0]=> array(6) { [0]=> string(1) "2" [1]=> string(1) "1" [2]=> string(10) "07-09-2016" [3]=> string(10) "08-09-2016" [4]=> string(1) "1" [5]=> string(6) "100.00" } [1]=> array(6) { [0]=> string(1) "2" [1]=> string(1) "1" [2]=> string(10) "07-09-2016" [3]=> string(10) "10-09-2016" [4]=> string(1) "3" [5]=> string(6) "450.00" } }

只是为了进一步说明,你不需要在字符串的第一部分中使用'2'来计算将它分成多少个数组,因为它们使用2个不同的分隔符,你可以很容易地解决它。保存为8位空格或某些'