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


how to format array from string in php?

我想如果字符串中的第一个数字是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');
?>

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);

这个过程假设字符串的格式是正确的,如果不是这样的话,它将会失败。

使用explode()函数!真的很酷。
我是这样解决这个问题的。你最终会得到一个二维数组和我的代码。你可以用$fourthStep[0]访问$arr1,用$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位的空间或者