我有一个在所有键上都有空格的数组。这给其他程序中的目标带来了问题,这些程序不能以空格为目标,而且在键中包含空格也是一种糟糕的做法。
我正在寻找一些东西,将删除关键空格,并替换为多维数组中的下划线。最有可能是一个递归函数?
在另一个问题中找到了类似的东西,但在值中进行了替换。
foreach ($all_regions as $key => $value){
$all_regions[$key] = strtolower(str_replace(' ', '_', $value));
}
除了键之外,几乎需要复制这一点。我遇到的问题是,我可以想到如何引用键本身,因为如果您尝试像上面的方法那样进行推送,它只会重新创建另一个带下划线的键。
数组的一个片段,这是它的深度。
Array
(
[0] => Array
(
[Line Identifier] => PID
[Set ID] => 1
[User ID] =>
[Requests] => Array
(
[0] => Array
(
[Line Identifier] => OBR
[Set ID] => 1
[Placer Order Number] => 021120091525
[Results] => Array
(
[0] => Array
(
[Line Identifier] => OBX
[Set ID] => 1
[1] => Array
(
[Line Identifier] => OBX
[Set ID] => 2
我试过下面的方法,但是Key element cannot be a reference
private function fixArrayKeys($array){
if(is_array($array)){
foreach($array as &$key => $value){
if(!is_array($key))
$array[strtolower(str_replace(' ', '_', $key))] = $value;
else
fixArrayKeys($array);
}
} else {
return $array;
}
}
发布于 2012-11-15 10:59:10
function fixArrayKey(&$arr)
{
$arr=array_combine(array_map(function($str){return str_replace(" ","_",$str);},array_keys($arr)),array_values($arr));
foreach($arr as $key=>$val)
{
if(is_array($val)) fixArrayKey($arr[$key]);
}
}
测试结果如下:
$data=array("key 1"=>"abc","key 2"=>array("sub 1"=>"abc","sub 2"=>"def"),"key 3"=>"ghi");
print_r($data);
fixArrayKey($data);
print_r($data);
这将输出以下内容:
Array
(
[key 1] => abc
[key 2] => Array
(
[sub 1] => abc
[sub 2] => def
)
[key 3] => ghi
)
Array
(
[key_1] => abc
[key_2] => Array
(
[sub_1] => abc
[sub_2] => def
)
[key_3] => ghi
)
发布于 2012-11-15 05:20:21
为什么不首先删除key中的空格呢
foreach ($all_regions as $key => $value){
$key = strtolower(str_replace(' ', '_', $key));
$all_regions[$key] = strtolower(str_replace(' ', '_', $value));
}
发布于 2012-11-15 05:25:52
请在下面尝试,虽然还没有测试过,但可以看到关键的区别
function fixArrayKeys(&$array)
{
if(is_array($array)){
foreach($array as &$key => $value){
if(!is_array($value))
$array[strtolower(str_replace(' ', '_', $key))] = $value;
else
fixArrayKeys(&$value);
}
} else {
return $array;
}
}
https://stackoverflow.com/questions/13391869
复制相似问题