所以,我有一个要“转换”的数组(只需将该数组的一些值添加到具有不同键的不同数组中)。最好的方法是什么?我目前有一种方法可以做到这一点,但我认为有更好的方法可以做到这一点。例如:一个 API 返回这个:[ 'id' => 1, 'title' => 'Response title', 'message' => 'Here is a message', 'clueless' => true, 'need_help' => true]但对于我的前端,我需要这个:[ 'task_id' => 1, 'text' => 'Response title', 'message' => 'Here is a message']请注意,这些值是相同的,但只有它们的键不同。此外,还有一些我不需要的值。我目前的方法是这样的:public function toSpecificFormat($data) { return [ 'task_id' => $data['id'], 'text' => $data['title'], 'message' => $data['message'] ];}
1 回答
一只甜甜圈
TA贡献1836条经验 获得超5个赞
根据您真正需要重写的字段数量,您可能希望创建这样的键映射:
$src = [
'id' => 1,
'title' => 'Response title',
'message' => 'Here is a message',
'clueless' => true,
'need_help' => true
];
$map = ['id' => 'task_id',
'title' => 'text',
'message' => 'messsage',
];
$result = [];
foreach($map as $from => $to) {
$result[$to] = $src[$from];
}
print_r($result);
但是,如果您有更多“重写”键,那么这是比手动复制更灵活的方法,但是如果一个只有几个(比如 2 个或 3 个),那么 OP 的代码就完全足够了,而且我的回答中显示的方式只是一个简单的过度工程。
- 1 回答
- 0 关注
- 145 浏览
添加回答
举报
0/150
提交
取消
