将数组元素作为字符串循环并将它们转换为子数组php

时间:2017-05-22 23:48:32

标签: php arrays for-loop curl

我一直在努力解决这个问题。我有一个从curl结果远程文本文件加载的数组。它是由空格和管道分隔的数字数据。我通过一系列preg_match运行curl结果来处理一些不规则性并用逗号分隔字段。

print_r 的结果如下所示

Array ( [0] => 
[1] => 18,3,1.28,4,1,1,0.97,16.9,25,0,0.58,9.7,8,0,0.55,12.6,37,0,0.23,6.5,99,,, 
[2] => 18,4,1.30,4,0,0,1.00,16.9,25,0,0.58,9.6,8,0,0.55,12.6,37,0,0.24,6.5,99,,, 
[3] => 18,5,1.32,4,0,1,1.03,16.9,24,0,0.57,9.6,8,0,0.54,12.6,37,0,0.25,6.4,98,,, 
[4] => 18,6,1.34,4,0,0,1.06,16.8,24,0,0.57,9.5,8,0,0.54,12.6,37,0,0.25,6.4,99,,, 
[5] => 18,7,1.36,5,0,0,0.67,16.0,35,0,0.56,9.2,7,0,0.55,12.6,36,0,0.25,6.4,99,,, 
[6] => 18,8,1.38,5,0,0,0.73,16.5,35,0,0.56,9.5,7,0,0.55,12.6,36,0,0.25,6.3,100,,, )

我想用逗号将字符串元素转换为子数组并循环遍历整个数组

除了一堆其他尝试之外,最接近我想达到的结果是:

for($i = 0; $i < count($done); $i++) {
    print_r (explode(',', $done[$i]));
  }

结果:

Array ( [0] => ) Array ( [0] => 18 [1] => 3 [2] => 1.28 [3] => 4 [4] => 1 [5] => 1 [6] => 0.97 [7] => 16.9 [8] => 25 [9] => 0 [10] => 0.58 [11] => 9.7 [12] => 8 [13] => 0 [14] => 0.55 [15] => 12.6 [16] => 37 [17] => 0 [18] => 0.23 [19] => 6.5 [20] => 99 [21] => [22] => [23] => ) Array ( [0] => 18 [1] => 4 [2] => 1.30 [3] => 4 [4] => 0 [5] => 0 [6] => 1.00 [7] => 16.9 [8] => 25 [9] => 0 [10] => 0.58 [11] => 9.6 [12] => 8 [13] => 0 [14] => 0.55 [15] => 12.6 [16] => 37 [17] => 0 [18] => 0.24 [19] => 6.5 [20] => 99 [21] => [22] => [23] => ) Array ( [0] => 18 [1] => 5 [2] => 1.32 [3] => 4 [4] => 0 [5] => 1 [6] => 1.03 [7] => 16.9 [8] => 24 [9] => 0 [10] => 0.57 [11] => 9.6 [12] => 8 [13] => 0 [14] => 0.54 [15] => 12.6 [16] => 37 [17] => 0 [18] => 0.25 [19] => 6.4 [20] => 98 [21] => [22] => [23] => )... )

期望的结果:

Array ( 
     [0] => Array ( [0] => 18 [1] => 3 [2] => 1.28 [3] => 4 [4] => 1 [5] => 1 [6] => 0.97 [7] => ...)
     [1] => Array ( [0] => 18 [1] => 4 [2] => 1.30 [3] => 4 [4] => 0 [5] => 0 [6] => 1.00 [7] => ...) 
     [2] => Array ( [0] => 18 [1] => 5 [2] => 1.32 [3] => 4 [4] => 0 [5] => 1 [6] => 1.03 [7] => ... )
 )

目标:

 echo $done[0][0] . ' ' . $done[0][1] . ' ' ... . '<br />'
      $done[1][0] . ' ' . $done[1][1] . ' ' ... . '<br />'; 

或类似的东西。

1 个答案:

答案 0 :(得分:2)

foreach ( $done as $d ) {
    if ( is_null( $d ) ) continue;
    $res[] = explode( ',', $d );
} 

先试试。