我从FORM
发送了此ARRAYArray
(
[0] => one
two
three
[1] => hello
how
are
)
由于这些值是通过textarea从表单发送的,所以它有断路器,所以我想将每一个更改为一个数组字段,如下所示:
Array
(
[0] => Array
(
[0] => one
[1] => two
[2] => three
)
[1] => Array
(
[0] => hello
[1] => how
[2] => are
)
)
这是我到目前为止所做的:
foreach ($array as &$valor) {
foreach(preg_split("/((\r?\n)|(\r\n?))/", $valor) as $line){
$arraynew[] = $line;
}
}
但我得到了这个结果
Array
(
[0] => one
[1] => two
[2] => three
[3] => hello
[4] => how
[5] => are
)
我做错了什么? :(
答案 0 :(得分:2)
对于POST数组中的每个键,将值弹出到最终数组,其值包含一个数组,其值表示POST数组的每一行值。
<?php
$data = array(
0 => "one\ntwo\nthree",
1 => "hello\nhow\nare"
);
$final = array();
for($i = 0; $i < count($data); $i++) {
$row = preg_split('/\n/', $data[$i]);
if(is_array($row)) {
for($j = 0; $j < count($row); $j++) {
$final[$i][] = $row[$j];
}
}
}
var_dump($final);
array(2) {
[0] =>
array(3) {
[0] =>
string(3) "one"
[1] =>
string(3) "two"
[2] =>
string(5) "three"
}
[1] =>
array(3) {
[0] =>
string(5) "hello"
[1] =>
string(3) "how"
[2] =>
string(3) "are"
}
}
答案 1 :(得分:1)
嗯,你真的太努力了。
array_map(function($e) { return explode("\n", $e); }, $orig_array);
就是你所需要的。如果你真的想要,可以使用preg_split
,但explode
就足够了。
答案 2 :(得分:0)
你可以简单地这样做
$array=array("one\ntwo\nthree","hello\nhow\nare");
$arraynew=array();
foreach ($array as &$valor) {
$arraynewtemp=array();
foreach(preg_split("/((\r?\n)|(\r\n?))/", $valor) as $line){
$arraynewtemp[] = $line;
}
array_push($arraynew,$arraynewtemp);
}
var_dump($arraynew);
将输出
array(2) {
[0]=>
array(3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
string(5) "three"
}
[1]=>
array(3) {
[0]=>
string(5) "hello"
[1]=>
string(3) "how"
[2]=>
string(3) "are"
}
}
这应该有效