将一个长字符串转换为二维数组PHP


Phrasing a long string to a 2d array PHP

我有一个长字符串,说"123~456!!789~012!!345~678!!901~234!!567~890!!1234~5678"。我已经习惯了此字符串中的分隔符类型~。有人能给我一个有效的方法来把这个字符串分解成2d数组吗。示例:

$txt = "123~456!!!789~012!!!345~678!!!901~234!!!567~890!!!1234~5678".

分解/拆分后的二维阵列。

array[0][0] = 123 ; array[0][1] = 456 ;
array[1][0] = 789 ; array[1][1] = 012 ; 
array[2][0] = 345 ; array[2][1] = 678 ;
array[3][0] = 901 ; array[3][1] = 234;
array[4][0] = 567 ; array[4][1] = 890;
array[5][0] = 1234 ; array[5][1] = 5678;

谢谢。:(

这就是它所需要的:

foreach(explode("!!!",$txt) AS $key => $subarray) {
    $array[$key] = explode("~",$subarray);
}
print_r($array);

快速高效,您将获得二维数组。

请参阅:http://3v4l.org/2fmdn

您可以使用preg_match_all()使用PREG_SET_ORDER,然后映射每个项目以消除零索引:

$txt = "123~456!!!789~012!!!345~678!!!901~234!!!567~890!!!1234~5678";
if (preg_match_all('/('d+)~('d+)/', $txt, $matches, PREG_SET_ORDER)) {
        $res = array_map(function($item) {
                return array_slice($item, 1);
        }, $matches);
        print_r($res);
}

或者,使用双explode():

$res = array_map(function($item) {
    return explode('~', $item, 2);
}, explode('!!!', $txt));
print_r($res);
$txt = "123~456!!!789~012!!!345~678!!!901~234!!!567~890!!!1234~5678".
$firstSplit = explode("!!!",$txt);
$newArray = array();

for($i=0;$i<sizeof($firstSplit);$i++){
  $secondSplit = explode("~",$firstSplit[$i]);
  for($j=0;$j<sizeof($secondSplit);$j++){
    $newArray[$i][] = $secondSplit[$j];
 }
}

我认为应该这样做。

看看preg_split()函数。

$txt = "123~456!!!789~012!!!345~678!!!901~234!!!567~890!!!1234~5678";
$array = preg_split ('/!!!|~/', $txt);
print_r($array);
Output: 
Array ( [0] => 123 [1] => 456 [2] => 789 [3] => 012 [4] => 345 [5] => 678 [6] => 901 [7] => 234 [8] => 567 [9] => 890 [10] => 1234 [11] => 5678 )