我有一个用“|”分隔的数组。我想做的是用这个标识符分开。
数组如下: -
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
)
答案 0 :(得分:2)
您可以使用preg_split
在|
和EOL:
$parts = preg_split('#(\||\r\n|\r|\n)#', $string); // EOL is actually 3 different types
这使得1个阵列包含9个元素。
或首先在EOL上爆炸,然后在|
上爆炸:
$lines = preg_split('#(\r\n|\r|\n)#', $string);
$lines = array_map(function($line) {
return explode('|', trim($line));
});
这使得3个数组各有3个元素。
答案 1 :(得分:2)
首先爆炸新行,又称"\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
)
)
答案 2 :(得分:1)
您可以使用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);
Sandbox example,如果你不需要它展平你可以放弃foreach部分:
$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);