我有多维数组
$a = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
然后我爆炸了$a
$array_a = explode("|", $a);
//loop
for($i=0;$i<=count($arr_a)-1;$i++){
arr_b = explode(",", $arr_a[$i]);
foreach($arr_b as $id => $access){
echo $id." have access ".$access;
}
}
//result
0 have access 5
1 have access add
0 have access 4
1 have access edit
0 have access 6
1 have access add
0 have access 6
1 have access edit
0 have access 19
1 have access add
0 have access 19
1 have access delete
0 have access 19
1 have access view
//-end result
问题是:
我怎样才能得到这样的结果
5 有权访问添加
4 拥有编辑权限
6 有权添加、编辑
19 有权添加、删除、查看
最佳答案
我认为在这种情况下,正则表达式会是更好的解决方案,以防您没有考虑使用它。
示例(已测试):
$a = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
$result = array();
// match each pair in the input
if (preg_match_all('/(\\d+)\\,(.*?)(\\||$)/m', $a, $matches)){
foreach( $matches[1] as $match_index => $match ){
$result[$match][] = $matches[2][$match_index];
}
}
// loop through the results and print in desired format
foreach( $result as $entry_index => $entry ){
echo "$entry_index have access " . implode( ',', $entry ) . "\n";
}
输出:
5 have access add
4 have access edit
6 have access add,edit
19 have access add,delete,view
使用正则表达式可以简化代码,并且可以更轻松地更改支持的输入格式。
$result 数组最终得到一个 HashMap ,使用您的数字 ID 作为键,使用权限数组(添加、删除等)作为每个键的值。
关于php - PHP 多维数组分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8578910/