PHP - 并置/级联多维数组键 [英] PHP - Concatenate / cascade multidimensional array keys
问题描述
我已经意识到我需要停下来撞我的头,寻求帮助......
I've realized I need to stop banging my head and ask for help...
我有以下数组:
$permissionTypes = array(
'system' => array(
'view' => 'View system settings.',
'manage' => 'Manage system settings.'
),
'users' => array(
'all' => array(
'view' => 'View all users.',
'manage' => 'Manage all users.'
)
),
'associations' => array(
'generalInformation' => array(
'all' => array(
'view' => 'View general information of all associations.',
'manage' => 'Manage general information of all associations.'
),
'own' => array(
'view' => 'View general information of the association the user is a member of.',
'manage' => 'Manage general information of the association the user is a member of.'
)
)
));
我试图瓦解/级联键为一维数组,像这样:
I'm trying to collapse / cascade the keys into a one-dimension array like so:
array(
'system_view',
'system_manage',
'users_all_view',
'users_all_manage',
'associations_generalInformation_all_view',
'associations_generalInformation_all_manage',
'associations_generalInformation_own_view',
'associations_generalInformation_own_manage'
)
我可以使用嵌套的循环,但阵列将是尺寸的未定义数量。
I could use nested loops, but the array will be an undefined number of dimensions.
这是我已经得到最接近的:
This is the closest I've gotten:
public function iterateKeys(array $array, $joiner, $prepend = NULL) {
if (!isset($formattedArray)) { $formattedArray = array(); }
foreach ($array as $key => $value) {
if(is_array($value)) {
array_push($formattedArray, $joiner . $this->iterateKeys($value, $joiner, $key));
} else {
$formattedArray = $prepend . $joiner . $key;
}
}
return $formattedArray;
}
任何想法?
推荐答案
我觉得这个应该这样做:
I think this should do it:
public function iterateKeys(array $array, $joiner, $prepend = NULL) {
if (!isset($formattedArray)) { $formattedArray = array(); }
foreach ($array as $key => $value) {
if(is_array($value)) {
$formatted_array = array_merge($formattedArray, $this->iterateKeys($value, $joiner, $prepend . $joiner . $key));
} else {
$formattedArray[] = $prepend . $joiner . $key;
}
}
return $formattedArray;
}
由于递归调用返回一个数组,你需要使用 array_merge
将它与你目前拥有相结合。而对于非数组的情况下,你需要新的字符串推到数组,而不是替换字符串数组。
Since the recursive call returns an array, you need to use array_merge
to combine it with what you currently have. And for the non-array case, you need to push the new string onto the array, not replace the array with a string.
这篇关于PHP - 并置/级联多维数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!