How to remove prefix in array keys

谁说我不能喝 提交于 2019-12-22 03:24:09

问题


I try to remove a prefix in array keys and every attempt is failing. What I want to achieve is to:

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

To Get: Array ( [Size] => 3 [Colour] => 7 )

Your help will be much appreciated...


回答1:


One of the ways To Get:Array ( [Size] => 3 [Colour] => 7 ) From your 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;

}

If you think there'll be multiple underscores in keys just replace first line inside foreach with list($dummy, $newkey) = explode('attr_', $key);




回答2:


If I understood your question, you don't have to use implode() to get what you want.

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 ) 



回答3:


Here's something else to chew on that can be reused for multiple arrays in your application that have different key prefixes. This would be useful if you have Redis prefixed keys to remap or something of that nature.

$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);

Output:

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


来源:https://stackoverflow.com/questions/8614397/how-to-remove-prefix-in-array-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!