在PHP中分解一个包含新行的数组


Explode an Array that has a new line in it in PHP

我有一个用"|"分隔的数组。我想做的是用这个标识符分隔。

阵列如下:-

myid1|My Title|Detailed Description
myid2|My Title|Second Row Description
myid3|My Title|Third row description

我所做的只是在上面使用explode来获得我想要的结果。

$required_cells = explode('|', $bulk_array);

但问题是(如下所示),由于"新行",只有我的第一个数组被正确分解,下一个数组的下一个第一个单元格被混合。

我有可能在连续的数组单元格中得到上面的数组吗?

Array
(
    [0] => myid1
    [1] => My Title 
    [2] => Detailed Description
myid2
    [3] => My Title 
    [4] => Second Row Description
myid3
    [5] => My Title 
    [6] => Second Row Description
)

在换行符上爆炸,也就是先进行"'n",然后循环通过该数组并在管道上爆炸,也称为'|'

$bulk_array = "myid1|My Title|Detailed Description
myid2|My Title|Second Row Description
myid3|My Title|Third row description";
$lines = explode("'n", $bulk_array);
foreach ($lines as $key => $line)
{
    $lines[$key] = explode('|', $line);
}

然后print_r($lines);将输出:

Array
(
    [0] => Array
        (
            [0] => myid1
            [1] => My Title
            [2] => Detailed Description
        )
    [1] => Array
        (
            [0] => myid2
            [1] => My Title
            [2] => Second Row Description
        )
    [2] => Array
        (
            [0] => myid3
            [1] => My Title
            [2] => Third row description
        )

)

您可以使用preg_split|和EOL:上爆炸

$parts = preg_split('#('||'r'n|'r|'n)#', $string); // EOL is actually 3 different types

它构成了一个包含9个元素的数组。

或者先在EOL上爆炸,然后在|:上爆炸

$lines = preg_split('#('r'n|'r|'n)#', $string);
$lines = array_map(function($line) {
  return explode('|', trim($line));
});

它构成3个阵列,每个阵列有3个元素。

您可以使用array_map:

$str = "myid1|My Title|Detailed Description
  myid2|My Title|Second Row Description
  myid3|My Title|Third row description";
$newLine = (explode("'n", $str));
$temp = array();
$result = array_map(function($someStr) use(&$temp) { 
  $exploded = explode("|", $someStr); 
  foreach($exploded as $value) $temp[] = $value;
}, $newLine); 
print_r($temp);

沙盒的例子,如果你不需要它变平,你可以放下前臂部分:

$str = "myid1|My Title|Detailed Description
  myid2|My Title|Second Row Description
  myid3|My Title|Third row description";
$newLine = (explode("'n", $str));
$result = array_map(function($someStr) { 
  return explode("|", $someStr); 
}, $newLine); 
print_r($result);