PHP将数组列表值转换为字段别名

时间:2016-12-20 14:34:46

标签: php arrays

我想将数组列表转换为字段别名。例如:

$keymap = ['id' => projectId, 'name' => projName];

然后从给出的数组中,我想做这个转换:

$keymap = ['id as projectId', 'name as projName'];

我的目标是从api获得json格式的响应然后我想根据$ keymap更改每个响应的键名。

任何想法如何?提前致谢

4 个答案:

答案 0 :(得分:2)

<?php
$keymap = ['id' => projectId, 'name' => projName];
$keymap2 = [];
foreach($keymap as $k => $v){
    $keymap2[] = $k.' as '.$v;
}
$keymap = $keymap2;

//你应该得到这个 $keymap = ['id as projectId', 'name as projName'];

答案 1 :(得分:2)

...替代

  $keymap = ['id' => projectId, 'name' => projName];
    function transform(&$item, $key){   
         $item = $key. ' as '.$item;
    }
    array_walk($keymap, 'transform');

答案 2 :(得分:1)

如下所示?

foreach($keymap as $key=>$value
{
    $new_array[] = $key.' as '.$value;
}
print_r($new_array);

答案 3 :(得分:1)

您可以使用以下方式实现此目的:

columns_to_keep = list()    
for c in df.columns.values:
    if c.isdigit():
        if int(c) > 1995:
            columns_to_keep.append(c)
    else:
        columns_to_keep.append(c)
df_copy = df[columns_to_keep]