grantiago grantiago - 1 year ago 48
PHP Question

loop through array elements as strings and convert them to sub arrays php

I've been trying for hours to solve this. I have an array loaded from a remote text file from a curl result. It is numerical data separated by spaces and pipes. I ran the curl result through a series of preg_match to deal with some irregularities and separate the fields with commas.

the result with print_r looks like this

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


I want to convert the string elements by comma to sub arrays and loop through the entire array

Along with a bunch of other attempts the closest I have come to the desired result is:

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


the result:

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] => )... )


the desired result:

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] => ... )
)


The goal:

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

or something like that.

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

Try it first.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download