4

我有这种类型的数组,其中包含每个月的总收入:

Array ( [Total_Income_JAN] => 5000 [Total_Income_FEB] => 8000 [Total_Income_MAR] => 10000 )

如何从数组键中删除前缀部分,使其变为:

Array ( [JAN] => 4321 [FEB] => 2364 [MAR] => 2364 ) 
4

5 回答 5

5

尝试这个:

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

?>

试用演示>>

于 2013-05-30T08:37:28.383 回答
5

首先,此解决方案适用于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)
);
于 2013-05-30T09:00:32.790 回答
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);
于 2013-05-30T08:37:31.887 回答
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);
于 2013-05-30T08:54:50.930 回答
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)
}
于 2021-03-17T14:11:52.030 回答