PHP-数组更改键名,动态保留值

时间:2018-07-19 07:29:13

标签: php laravel

我正在从XML文件加载数据,并且还试图动态地能够将XML元素中的这些值匹配到我的数据库表中。 我正在使用Laravel 5.6

这就是我现在拥有的:

config.php

'milestone' => [
     'columns'  => array(       
         "JobDept"                      => "department",
         "JobBranch"                    => "branch",
         "Destination"                  => "destination",
      ),
 ],

上面的数组具有以下格式,该格式将我的XML文件映射到我的数据库列:

"XML Element Name => Database Column Name"

因此,我现在可以从数组(JobDept, JobBranch, Destination)中获取密钥,并在我的XML文件中找到它们:

$data = $xml->parse([
    'report' => ['uses' => 'item['.implode(",",$xmlFilters).']', 'default' => null]
]);

以上工作正常。这将使用我的XML文件中的实际值填充键:

0 => array:3 [▼
  "JobDept" => "FEA"
  "JobBranch" => "AAL"
  "Destination" => "TWTPE"
]

这就是我被困住的地方。由于我在MySQL数据库中的列名是department, branch, destination,我猜测我需要更改数组键名以匹配我的数据库列名,因此数组将如下所示:

0 => array:3 [▼
  "department" => "FEA"
  "branch" => "AAL"
  "destination" => "TWTPE"
]

关于如何动态实现此目标的任何想法?如上所述,我正在使用Laravel 5.6作为框架。

更新: 这是我的$data数组:

"report" => array:1[▼
        0 => array:3 [▼
          "JobDept" => "FEA"
          "JobBranch" => "AAL"
          "Destination" => "TWTPE"
        ]
 ]

1 个答案:

答案 0 :(得分:2)

一个简单的示例(fiddle):

$array = [
    "JobDept" => "FEA",
    "JobBranch" => "AAL",
    "Destination" => "TWTPE",
];
$replace = [
    "JobDept"                      => "department",
    "JobBranch"                    => "branch",
    "Destination"                  => "destination",
];

$new_array = [];
foreach ($array as $k => $v) {
    $new_array[$replace[$k]] = $v;
}
print_r($new_array);