explode - Convert string of months with data into a two dimensional array -
explode - Convert string of months with data into a two dimensional array -
good morning!
i have string number of various months each month followed series of numbers. need break string 2 dimensional array: months in first column columns of numbers after them.
i've worked out solutions using strtok, explode , month lookup table. solutions seem cumbersome. appreciate elegant, simple solution real coding experience use. string , hoped 2d array result below.
thank expertise , time!
dec 14 1938.50 1964.50 1935.75 1959.75 21.75 1960.25 1551405 2751445 mar 15 1931.00 1956.2 1928.0 1952.0 21.75 1952.50 2244 5495 jun 15 1920.25 1949.0 1920.25 1945.0 22.00 1945.50 88 350 sep 15 1925.00 1937.7 1925.00 1937.7 21.75 1938.75 6 204 dec 15 1935.75 1935.75 1935.75 1935.75 22.00 1932.75 1 212
ends being: dec 14 1938.50 1964.50 1935.75 1959.75 21.75 1960.25 1551405 2751445 mar 15 1931.00 1956.2 1928.0 1952.0 21.75 1952.50 2244 5495 etc...
the next should trick:
class="lang-php prettyprint-override">$data = "dec 14 1938.50 1964.50 1935.75 1959.75 21.75 1960.25 1551405 2751445 mar 15 1931.00 1956.2 1928.0 1952.0 21.75 1952.50 2244 5495 jun 15 1920.25 1949.0 1920.25 1945.0 22.00 1945.50 88 350 sep 15 1925.00 1937.7 1925.00 1937.7 21.75 1938.75 6 204 dec 15 1935.75 1935.75 1935.75 1935.75 22.00 1932.75 1 212"; $dataarray = preg_split('|\s+|', $data); $table = array(); $idx = -1; // -1 because first array index should 0 foreach ($dataarray $elem) { if (preg_match('|^[a-z]{3}$|', $elem)) { $table[++$idx] = array('month' => $elem, 'values' => array()); } elseif (isset($table[$idx])) // in case first word not month { $table[$idx]['values'][] = $elem; } }
this gives next result:
class="lang-none prettyprint-override">array ( [1] => array ( [month] => dec [values] => array ( [0] => 14 [1] => 1938.50 [2] => 1964.50 [3] => 1935.75 [4] => 1959.75 [5] => 21.75 [6] => 1960.25 [7] => 1551405 [8] => 2751445 ) ) [2] => array ( [month] => mar [values] => array ( [0] => 15 [1] => 1931.00 [2] => 1956.2 [3] => 1928.0 [4] => 1952.0 [5] => 21.75 [6] => 1952.50 [7] => 2244 [8] => 5495 ) ) … )
note: simpler array structure, using month key, not work, because of months appear several times (e.g. dec
), , values overwritten.
arrays explode strtok
Comments
Post a Comment