[英]Renaming a key in a multidimensional array
I want to change key name in a multidimensional array. 我想更改多维数组中的键名。
My array: 我的数组:
Array
(
[0] => Array
(
[id] => 1
[fruit namé] => Banana
)
[1] => Array
(
[id] => 2
[fruit namé] => Apple
)
)
My function: 我的功能:
function renameFields($old, $new, $arr) {
foreach ($arr as $k=>$v) {
$arr[$k][$new] = $arr[$k][$old];
unset($arr[$k][$old]);
}
}
renameFields("fruit namé", "name", $arr);
- -
It works for id
but not when there an accent like fruit namé
. 它适用于
id
但在带有fruit namé
的重音时fruit namé
。
- -
EDIT 编辑
I know it's a bad practice to have some special char as key, but this datas came from a French system... 我知道将一些特殊的char作为键是不好的做法,但是这些数据来自法国系统。
You need to either a) pass $arr
to your function by reference or b) have renameFields
return the updated array. 您需要a)通过引用将
$arr
传递给您的函数,或者b)让renameFields
返回更新后的数组。
Your code currently modifies a copy of the $arr
array (because that's what gets passed to renameFields
when it's called), and never updates the one that exists outside of the renameFields
function. 您的代码当前正在修改
$arr
数组的副本(因为这是在调用它时传递给renameFields
的内容),并且永远不会更新renameFields
函数外部的renameFields
。
So, you need to either do: 因此,您需要执行以下任一操作:
function renameFields($old, $new, &$arr) {
foreach ($arr as $k=>$v) {
$arr[$k][$new] = $arr[$k][$old];
unset($arr[$k][$old]);
}
}
renameFields("fruit name", "name", $arr);
Which will pass $arr
by reference. 它将通过引用传递
$arr
。
Or: 要么:
function renameFields($old, $new, $arr) {
foreach ($arr as $k=>$v) {
$arr[$k][$new] = $arr[$k][$old];
unset($arr[$k][$old]);
}
return $arr;
}
$arr = renameFields("fruit name", "name", $arr);
Which will have the function return the updated array and then you need to then update the variable. 它将使函数返回更新后的数组,然后您需要更新变量。
PS You don't need global $arr;
PS:您不需要
global $arr;
in either case here. 无论哪种情况。
It isn't a good idea to use spaces in your key names. 在键名中使用空格不是一个好主意。 You can do it but it's bad practice.
您可以做到,但这是不好的做法。
Here is what I came up with: 这是我想出的:
$my_array = array(
array(
'id' => 1,
'fruit name' => 'Banana'
),
array(
'id' => 2,
'fruit name' => 'Apple'
)
);
function renameFields($old, $new, $arr) {
$new_a = array();
foreach ($arr as $a) {
$new_a[] = array(
'id' => $a['id'],
$new => $a[$old]
);
}
return $new_a;
}
$new_array = renameFields("fruit name", "name", $my_array);
echo "<pre>";
print_r($new_array);
echo "</pre>";
It is a much better idea to pass the array to the function rather than using a global. 将数组传递给函数而不是使用全局函数是一个更好的主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.