例如
operation.user.add
operation.user.edit
operation.permission.add
performance.tool.add
performance.tool.remove
operation.permission.edit
operation.tool.delete
operation.tool.remove
希望结果如下:
Array
(
['operation'] => Array
(
['user'] => Array
(
[0] => 'add',
[1] => 'edit'
),
['permission'] => Array
(
[0] => 'add',
[1] => 'edit'
),
['tool'] => Array
(
[0] => 'delete',
[1] => 'remove'
),
),
['performance'] => Array
(
['tool'] => Array
(
[0] => 'add',
[1] => 'remove'
)
)
)
有人可以提供解决方案,如何将字符串转换为上述数组?
缩放是一个字符串值,这可能是您所能获得的,这可能是效率的:
$str = 'operation.user.add
operation.user.edit
operation.permission.add
performance.tool.add
performance.tool.remove
operation.permission.edit
operation.tool.delete
operation.tool.remove';
$output = [];
foreach (explode("\n", $str) as $string) {
$parts = explode('.', $string);
$output[$parts[0]][$parts[1]][] = $parts[2];
}
print_r($output);
输出:
Array
(
[operation] => Array
(
[user] => Array
(
[0] => add
[1] => edit
)
[permission] => Array
(
[0] => add
[1] => edit
)
[tool] => Array
(
[0] => delete
[1] => remove
)
)
[performance] => Array
(
[tool] => Array
(
[0] => add
[1] => remove
)
)
)
如果您将字符串存储到阵列中,那么您可以像下面这样做
Array
(
[operation] => Array
(
[user] => Array
(
[0] => add
[1] => edit
)
[permission] => Array
(
[0] => add
[1] => edit
)
[tool] => Array
(
[0] => delete
[1] => remove
)
)
[performance] => Array
(
[tool] => Array
(
[0] => add
[1] => remove
)
)
)
$str = 'operation.user.add
operation.user.edit
operation.permission.add
performance.tool.add
performance.tool.remove
operation.permission.edit
operation.tool.delete
operation.tool.remove';
$output = [];
foreach (explode("\n", $str) as $string) {
$parts = explode('.', $string);
$output[$parts[0]][$parts[1]][] = $parts[2];
}
print_r($output);