我有多维数组
$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有访问添加,删除,查看
答案 0 :(得分:2)
在这种情况下,我认为Regex会是一个更好的解决方案,如果您没有考虑使用它。
示例(已测试):
$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数组以哈希映射结束,使用您的数字ID作为键和权限数组(添加,删除等)作为每个键的值。
答案 1 :(得分:1)
试试这个(测试过):
// intial data
$strAccess = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
// build access array
$arrayAccess = array();
$tmpList = explode('|', $strAccess);
foreach($tmpList as $access)
{
list($idUser, $right) = explode(',', $access);
if (!isset($arrayAccess[$idUser]))
$arrayAccess[$idUser] = array();
$arrayAccess[$idUser][] = $right;
}
// print it out
foreach($arrayAccess as $idUser => $accessList)
echo $idUser." has access ".implode(",", $accessList)."\n";
答案 2 :(得分:0)
$a = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
$array_a = explode("|". $a);
//loop
$aRights = array();
for($i=0;$i<=count($arr_a)-1;$i++){ $arr_b = explode(",", $arr_a[$i]);
foreach($arr_b as $id => $access){
$aRights[$id][] = $access;
}
}
foreach( $aRights as $id=>$rightsList){
echo $id." have access ";
$i=1;
foreach($rightsList as $r){
echo $r;
if($i != count($rightsList)) echo ",";
$i++;
}
}
答案 3 :(得分:0)
您可以使用类似
的计数器 $count5=0;
foreach($arr_b as $id => $access){
if($access=='5'){
$count5++;
}
echo $id." have access ".$count5;
}
答案 4 :(得分:0)
像hashmapping这样的东西:
$tobegenerated = array();
$a = explode(yourdelimiter,yourstring);
foreach ($a as $cur)
{
$b = explode(delimiter,$cur);
$tobegenerated[$cur[0]] = $cur[1];
}
//Print hashmap $tobegenerated
这应该有用,请记住在php数组中也是哈希映射
编辑1: PHP中的数组是哈希映射。哈希映射可以解释为一个数组,其中键可以是任何东西,值也可以是任何值。在这种情况下,您希望使用哈希映射,因为您需要绑定“超出”数组范围的值(即使它们是整数)。因此,哈希映射正是您想要的,允许将任何内容指定为键。