Php 如何编辑数组';钥匙是什么?
制作完密钥后,是否可以对其进行编辑 我知道你可以用不同的键创建一个数组,但是我在php网站上看不到任何关于编辑键的内容 原始阵列:Php 如何编辑数组';钥匙是什么?,php,arrays,Php,Arrays,制作完密钥后,是否可以对其进行编辑 我知道你可以用不同的键创建一个数组,但是我在php网站上看不到任何关于编辑键的内容 原始阵列: Array ( [0] => first [1] => color ) 我想要的是: Array ( [newName] => first [1] => color ) 这几乎是唯一可以做的事情。如果要更改项的键,必须使用新键和旧键设置值(此技术更改数组的顺序): 或者使用放弃循环并允许您修改密钥的包装器,
Array
(
[0] => first
[1] => color
)
我想要的是:
Array
(
[newName] => first
[1] => color
)
这几乎是唯一可以做的事情。如果要更改项的键,必须使用新键和旧键设置值(此技术更改数组的顺序): 或者使用放弃循环并允许您修改密钥的包装器,例如:
function array_change_key(&$array, $search, $replace) {
$keys = array_keys($array);
$values = array_values($array);
// Return FALSE if replace key already exists
if(array_search($replace, $keys) !== FALSE) return FALSE;
// Return FALSE if search key doesn't exists
$searchKey = array_search($search, $keys);
if($searchKey === FALSE) return FALSE;
$keys[$searchKey] = $replace;
$array = array_combine($keys, $values);
return TRUE; // Swap complete
}
这里有一种替代的简单方法,只要您在一次调用中对每个数组执行所有的重新设置密钥,这种方法可能相当有效:
<?php
function mapKeys(array $arr, array $map) {
//we'll build our new, rekeyed array here:
$newArray = array();
//iterate through the source array
foreach($arr as $oldKey => $value) {
//if the old key has been mapped to a new key, use the new one.
//Otherwise keep the old key
$newKey = isset($map[$key]) ? $map[$key] : $oldKey;
//add the value to the new array with the "new" key
$newArray[$newKey] = $value;
}
return $newArray;
}
$arr = array('first', 'color');
$map = array(0 => 'newName');
print_r(mapKeys($arr, $map));
更改数组顺序的
。
function array_change_key(&$array, $search, $replace) {
$keys = array_keys($array);
$values = array_values($array);
// Return FALSE if replace key already exists
if(array_search($replace, $keys) !== FALSE) return FALSE;
// Return FALSE if search key doesn't exists
$searchKey = array_search($search, $keys);
if($searchKey === FALSE) return FALSE;
$keys[$searchKey] = $replace;
$array = array_combine($keys, $values);
return TRUE; // Swap complete
}
<?php
function mapKeys(array $arr, array $map) {
//we'll build our new, rekeyed array here:
$newArray = array();
//iterate through the source array
foreach($arr as $oldKey => $value) {
//if the old key has been mapped to a new key, use the new one.
//Otherwise keep the old key
$newKey = isset($map[$key]) ? $map[$key] : $oldKey;
//add the value to the new array with the "new" key
$newArray[$newKey] = $value;
}
return $newArray;
}
$arr = array('first', 'color');
$map = array(0 => 'newName');
print_r(mapKeys($arr, $map));