我有这种类型的数据包含每个月的总收入:
Array ( [Total_Income_JAN] => 5000 [Total_Income_FEB] => 8000 [Total_Income_MAR] => 10000 )
如何从数组键中删除前缀部分,使其变为:
Array ( [JAN] => 4321 [FEB] => 2364 [MAR] => 2364 )
答案 0 :(得分:3)
试试这个:
<?php
$list = Array("Total_Income_JAN" => 5000, "Total_Income_FEB" => 8000 , "Total_Income_MAR" => 10000);
function removePrefix(array $input) {
$return = array();
foreach ($input as $key => $value) {
if (strpos($key, 'Total_Income_') === 0)
$key = substr($key, 13);
if (is_array($value))
$value = removePrefix($value);
$return[$key] = $value;
}
return $return;
}
$list = removePrefix($list);
print_r($list);
?>
答案 1 :(得分:3)
首先,此解决方案适用于php 5.3.x
及更高版本。
它将两个数组首先组合成键,将第二个值组合成原始数组。虽然使用array_map
转换了密钥,但使用str_replace
删除了不需要的部分。
$my_array2 = array_combine(
array_map(
function($k) { return str_replace("Total_Income_", "", $k); },
array_keys($my_array)
),
array_values($my_array)
);
答案 2 :(得分:2)
试试这个
foreach($my_array as $key => $value)
{
$key2 = trim('Total_Income',$key); //or preg_replace('Total_income','',$key)
$my_array2[$key2] = $value;
}
print_r($my_array2);
答案 3 :(得分:0)
试试这个:
$old_array = Array ( 'Total_Income_JAN' => 5000, 'Total_Income_FEB' => 8000, 'Total_Income_MAR' => 10000 );
$new_array = array();
foreach($old_array as $key=>$val){
$new_key = preg_replace('#Total_Income_(.+)#i','$1',$key);
$new_array[$new_key] = $val;
}
echo '<pre>';print_r($new_array);
答案 4 :(得分:0)
这是基于@VijayaPandey 的答案的改进通用解决方案。 他的方法是硬编码的,所以我创建了一个更好的解决方案:
使用这样的方法:
$list = Array("Total_Income_JAN" => 5000, "Total_Income_FEB" => 8000 , "Total_Income_MAR" => 10000);
$list = stripArrayKeyPrefix($list, "Total_Income_");
var_dump($list);
function stripArrayKeyPrefix(array $input, $prefix)
{
$return = array();
foreach ($input as $key => $value) {
if (strpos($key, $prefix) === 0)
$key = substr($key, strlen($prefix));
if (is_array($value))
$value = removePrefix($value, $prefix);
$return[$key] = $value;
}
return $return;
}
array(3) {
["JAN"]=>
int(5000)
["FEB"]=>
int(8000)
["MAR"]=>
int(10000)
}