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.
The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.
Just make a note of the old value, use unset to remove it from the array then add it with the new key and the old value pair. Save this answer.
Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.
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;
}
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With