我的意见是:
$str = ' 1. Admin, Administrator,3. Visor, Super,4. Team, Super User,5. lastname, employee'
如何使用数组爆炸产生以下输出?
array(
[0] => Array ( [0] => 1 [1] => Admin [2] => Administrator)
[1] => Array ( [0] => 3 [1] => Visor [2] => Super)
[2] => Array ( [0] => 4 [1] => Team [2] => Super User)
[3] => Array ( [0] => 5 [1] => lastname [2] => employee)
)
答案 0 :(得分:6)
<?php
$str = '1. Admin, Administrator,3. Visor, Super,4. Team, Super User,5. lastname, employee';
$str = str_replace('.', ',', $str);
$arr = explode(',', $str);
$arr = array_chunk ($arr, 3);
var_export($arr);
答案 1 :(得分:1)
这是另一种选择......这不是一种非常安全的获取数据的方法,但只要输入完全以这种格式完成,这就行了。主要的区别是这个修剪了空白。
你也可以使用另一个答案,然后在开始之前先做str_replace('',''
$myString="1. Admin, Administrator,3. Visor, Super,4. Team, Super User,5. lastname, employee";
$myOutput=array();
$myFirstSplit = explode(",",$myString);
foreach($myFirstSplit as $myKey=> $myVal){
$myNextSplit=explode('.',$myVal);
if(count($myNextSplit) > 1){
$myOutput[$myKey]=array(trim($myNextSplit[0]),trim($myNextSplit[1]));
}else{
$myOutput[$myKey-1][]=trim($myNextSplit[0]);
}
}
var_dump($myOutput);
答案 2 :(得分:1)
另一个修改输出的解决方案,比srain的(不错)解决方案快一点:
$str = '1. Admin, Administrator,3. Visor, Super,4. Team, Super User,5. lastname, employee';
$tok = strtok($str, ".,");
$output = array();
while ($tok !== false) {
$output[] = trim($tok);
$tok = strtok(".,");
}
$output = array_chunk($output, 3);
echo '<pre>';
print_r($output);