我正在使用sencha和php。数据从sencha返回为数组:
$permissionArr = Array([0] =>1_2 ,[1] =>"1_3", [2] =>1_4, [3] =>2_3, [4] =>"2_4",[5] =>"2_5");
我想使用上述数组的值创建一个数组。
array[
[0]=>[
'moduleId' => 1,
'permission' => '2,3,4'
]
]
我试图解决,但我认为我没有遵循正确的方法。
$permissionArr = Array("0" =>1 ,"1" =>"1_3", "2" =>2, "3" =>3, "4" =>"3_1","5" =>"3_2","6" =>4,"7" =>"4_1");
$finalArr = array();
foreach($permissionArr as $key => $value) {
if(stristr( $value, '_') ){
array_push($finalArr, $value);
}
}
$aa = array();
foreach($finalArr as $key => $val){
$permissionArray = explode( '_', $val);
array_push($aa, $permissionArray);
}
答案 0 :(得分:2)
您在这里:
<?php
$permissionArr = array("0" =>1 ,"1" =>"1_3", "2" => "1_4", "3" => "3", "4" =>"3_1","5" =>"3_2","6" =>"4","7" =>"4_1");
$groupedPermArr = array_reduce(
$permissionArr,
function ($output, $value) {
$values = explode('_', $value);
$output[$values[0]]['module_id'] = $values[0];
if (isset($values[1])) {
$output[$values[0]]['permission'][] = $values[1];
}
return $output;
},
[]
);
$stringifiedPermArr = array_map(
function ($value) {
$value['permission'] = implode(',', array_unique($value['permission']));
return $value;
},
$groupedPermArr
);
var_dump($stringifiedPermArr);
说明: 1.首先使用键“ module_id”和“ permission”创建一个数组数组。 2.其次,对该数组进行迭代,确保权限是唯一的,并使用分隔符将它们加入。
答案 1 :(得分:1)
过程:
isset()
确定每个当前值是否是module_id的第一个出现。array_values()
重新索引结果数组。代码:(Demo)
$permissionArr = ["1", "1_3", "1_4", "3", "3_1", "3_2","4", "4_1"];
foreach($permissionArr as $v) {
if(strpos($v, "_") !== false) { // logically you could safely omit "!== false" here
$x = explode("_", $v);
if (!isset($result[$x[0]])) {
$result[$x[0]] = ['module_id' => $x[0], 'permission' => $x[1]];
} else {
$result[$x[0]]['permission'] .= ",$x[1]";
}
}
}
var_export(array_values($result));
输出:
array (
0 =>
array (
'module_id' => '1',
'permission' => '3,4',
),
1 =>
array (
'module_id' => '3',
'permission' => '1,2',
),
2 =>
array (
'module_id' => '4',
'permission' => '1',
),
)
p.s。关于stristr()
...
i
引起的不区分大小写。strstr()
页上有一条注释,指出仅检查字符串中是否存在子字符串时,strpos()
是一个更轻便/更有效的调用。答案 2 :(得分:0)
此算法将使所有模块具有烫发功能。如果没有权限,那么您将有一个空数组。您需要测试模块烫发的良好ID,并且您将始终拥有模块数据。
// input array
$permissionArr = Array("0" =>1 ,
"1" =>"1_3",
"2" =>"1_4",
"3" =>3,
"4" =>"3_1",
"5" =>"3_2",
"6" =>4,
"7" =>"4_1");
//walk over array and form a new one with module id as key and perm as value array
foreach($permissionArr as $value){
$data = explode('_',$value);
$permission = $data[1]??null;
if($permission){
$raw[$data[0]][] = $permission;
}else{
if(!isset($raw[$data[0]])){
$raw[$data[0]] = [];
}
}
}
// transform new array in desired form
$result = array_walk($raw, function(&$val, $key){
$val = ['moduleId' => $key, 'permission' => implode(",",$val)] ;
}, $raw);
print_r($raw);