开发者

PHP: Split string into 2D array

I have a string which contains quite a bit of data. I want to split the data into a 2D array. The data in the string is split by a ~ (tilde) for the columns and a : (colon) for the different rows.

An example开发者_运维技巧 string could be: "London~10~20~cold:New York~23~53~hot:Madrid~43~12~dry".

Thanks.


$string = "London~10~20~cold:New York~23~53~hot:Madrid~43~12~dry";
$array = explode(':', $string);
foreach($array as &$value) $value = explode('~', $value);


Functional way (PHP 5.3.x needed):

$string = "London~10~20~cold:New York~23~53~hot:Madrid~43~12~dry";
$map = array_map(function($el) {
    return explode('~', $el);
}, explode(':', $string));


Another alternative would be:

preg_match_all('/(.*?)~(.*?)~(.*?)~(.*?)(?:$|:)/', $string, $array,
PREG_SET_ORDER);

It's more cumbersome in that you have to predefine the column format. It also returns the complete match in each rows [0]. Otherwise (due to PREG_SET_ORDER) it's in your desired 2d format.

Just posting it here to please and annoy the microoptimizers at the same time. Despite the common Stackoverflow meme, the regex is three times faster than the explode loop.


You can split data in php with explode(). So first you have to split the string, than you have to split your entries again with explode().

$data = explode(':', $string);
$array = array();
foreach($data as $d) {
    $d = explode('~', $d);
    $array[] = $d; //e.g. $array[0][0] --> London
    //$array[$d[0]] = array('temperature' => $d[1], 'dont-know' => $d[2], 'climate' => $d[3]); //e.g. $arra['London'] => array(...)
}


A "functional" style

$array = array_map(function($value) {
 return explode('~', $value);
}, explode(':',$string););
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜