如何删除数组键中的前缀

时间:2011-12-23 09:40:53

标签: php arrays key implode

我尝试删除数组键中的前缀,并且每次尝试都失败。我想要达到的目的是:

拥有:Array ( [attr_Size] => 3 [attr_Colour] => 7 )

获取:Array ( [Size] => 3 [Colour] => 7 )

非常感谢您的帮助......

3 个答案:

答案 0 :(得分:4)

如果我理解了您的问题,您就不必使用implode()来获得您想要的内容。

define(PREFIX, 'attr_');

$array = array('attr_Size' => 3, 'attr_Colour' => 7);

$prefixLength = strlen(PREFIX);

foreach($array as $key => $value)
{
  if (substr($key, 0, $prefixLength) === PREFIX)
  {
    $newKey = substr($key, $prefixLength);
    $array[$newKey] = $value;
    unset($array[$key]);
  }
}

print_r($array); // shows: Array ( [Size] => 3 [Colour] => 7 ) 

答案 1 :(得分:3)

获取方式之一:Array ( [Size] => 3 [Colour] => 7 )来自Having: Array ( [attr_Size] => 3 [attr_Colour] => 7 )

$new_arr = array();
foreach($Your_arr as $key => $value) {

list($dummy, $newkey) = explode('_', $key);
$new_arr[$newkey] = $value;

}

如果您认为密钥中会有多个下划线,只需用list($dummy, $newkey) = explode('attr_', $key);替换foreach中的第一行

答案 2 :(得分:0)

这里还有其他可以咀嚼的东西可以重复用于应用程序中具有不同键前缀的多个数组。如果你有重新映射的Redis前缀键或那种性质的东西,这将非常有用。

$inputArray = array('attr_test' => 'test', 'attr_two' => 'two');

/**
 * Used to remap keys of an array by removing the prefix passed in
 *
 * Example:
 * $inputArray = array('app_test' => 'test', 'app_two' => 'two');
 * $keys = array_keys($inputArray);
 * array_walk($keys, 'removePrefix', 'app_');
 * $remappedArray = array_combine($keys, $inputArray);
 *
 * @param $value - key value to replace, should be from array_keys
 * @param $omit - unused, needed for prefix call
 * @param $prefix - prefix to string replace in keys
 */
function removePrefix(&$value, $omit, $prefix) {
    $value = str_replace($prefix, '', $value);
}

// first get all the keys to remap
$keys = array_keys($inputArray);

// perform internal iteration with prefix passed into walk function for dynamic replace of key
array_walk($keys, 'removePrefix', 'attr_');

// combine the rewritten keys and overwrite the originals
$remappedArray = array_combine($keys, $inputArray);

// see full output of comparison
var_dump($inputArray);
var_dump($remappedArray);

输出:

array(2) {
  'attr_test' =>
  string(4) "test"
  'attr_two' =>
  string(3) "two"
}
array(2) {
  'test' =>
  string(4) "test"
  'two' =>
  string(3) "two"
}