Dưới đây là một số thứ khác để nhai trên đó có thể được sử dụng lại cho nhiều mảng trong ứng dụng của bạn có các tiền tố khóa khác nhau. Điều này sẽ hữu ích nếu bạn có Redis tiền tố để remap hoặc một cái gì đó của bản chất đó.
$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"
}
Vì vậy, bạn chỉ muốn loại bỏ 'attr_' từ khóa mảng của bạn? Điều này có liên quan gì với 'implode()'? 'Attr_my_prop' có nên trở thành' my_prop', 'prop' hay cái gì khác không? Quan trọng nhất, tại sao? Chúng tôi có thể thấy mã "không thành công" của bạn không? –