在PHP中的另一个数组值替换一个数组键

在PHP中的另一个数组值替换一个数组键

本文介绍了在PHP中的另一个数组值替换一个数组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想表单字段映射到数据库字段。

I want to map form fields to database fields.

我有两个数组。

一个阵列是数据并包含窗体域ID作为键,表单字段值的值。

One array is the data and contains the form field id as the key and the form field value as the value.

$data = array("inputEmail"=>"[email protected]","inputName"=>"someone"... etc

我也有一个数组,我打算作为地图使用。这个数组的键是一样的表单字段和值是数据库字段名。

I also have an array which i intended to use as a map. The keys of this array are the same as the form fields and the values are the database field names.

$map = array("inputEmail"=>"email", "inputName"=>"name"... etc

我想要做什么是迭代的数据阵列,其中数据密钥相匹配的地图密钥分配一个新的关键数据阵列是地图数组的值过。

What i want to do is iterate over the data array and where the data key matches the map key assign a new key to the data array which is the value of the map array.

$newArray = array("email"=>"[email protected]", "name"=>"someone"...etc

我的问题是怎么样?香港专业教育学院尝试了很多不同的方式,现在即时通讯完全对它失去了。

My question is how? Ive tried so many different ways im now totally lost in it.

推荐答案

这是由相当不错了foreach循环

This is made quite nice with a foreach loop

foreach( $data as $origKey => $value ){
  // New key that we will insert into $newArray with
  $newKey = $map[$origKey];
  $newArray[$newKey] = $value;
}

一个更简洁的方法(用于澄清消除变量)

A more condensed approach (eliminating variable used for clarification)

foreach( $data as $origKey => $value ){
  $newArray[$map[$origKey]] = $value;
}

这篇关于在PHP中的另一个数组值替换一个数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:37