6

I want to map form fields to database fields.

I have two arrays..

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.

3
  • Why not simply having the same names across the application? ;) Commented Mar 31, 2013 at 22:51
  • The input field names are important for the form validation to work. But i know what you mean. I thought this would be simpler than changing the whole applications input field names and also the validation script. Commented Mar 31, 2013 at 22:55
  • If I could give an advice: Try to use the same names across application if any possible. You'll be saved from many, many headaches. Also it is good for automatic code generation and so on... Commented Mar 31, 2013 at 22:58

2 Answers 2

12

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;
}
Sign up to request clarification or add additional context in comments.

Comments

10

If you want to replace keys of one array with values of the other the solution is array_combine

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

print_r output

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

4 Comments

array_combine does not do what the user is after in this instance.
@SamLanning as per the title Replace one arrays keys with another arrays values in php the above answer is correct so better not to negative rate it. As it can help people who want to replace keys of one array with values of the other.
array_combine() expects both arrays to be of equal length. One cannot assume that is the case here.
This is awsome solutions. Easiest. Should have been acepted. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.