Reputation: 1961
I have two array. and I want to concatenate to following format. format is shown as follows.
Getting form values using post method
/************ Getting Form names like Weight,arms Age etc **********************/
foreach ($_POST["form_field_names"] as $key => $values) {
$form_field_name = $values;
}
/************ Getting Form Values like 45,90,2 **********************/
foreach ($_POST["form_field_values"] as $key => $values) {
$form_field_values[] = $values;
}
Array
(
[0] => Age
[1] => Weight
[2] => Arms
)
Array
(
[0] => 45
[1] => 90
[2] => 2
)
Want to concatenate to following format
$output = $Age.","."45".",".$Weight.","."90".",".$Arms.","."2".",";
Upvotes: 1
Views: 71
Reputation: 28755
$str = '';
foreach($array1 as $key => $value)
{
$str .= $value.",". $array2[$key].",";
}
Upvotes: 0
Reputation: 1470
Seems like an odd request, but ok... ;)
$output = "";
for ($i = 0; $i < count($array1); $i++) {
$output .= $array1[$i] . "," . $array2[$i] . ",";
}
Now, that will concatenate the strings in array1. If you're looking to concatenate the variables named after the strings in array1, a very similar loop should work:
$output = "";
for ($i = 0; $i < count($array1); $i++) {
$output .= $$array1[$i] . "," . $array2[$i] . ",";
}
I think that should work.
Upvotes: 2
Reputation: 16768
You can 'merge' your parallel arrays
I'll call your first array $arr1
and the second $arr2
$newArr = array();
foreach($arr1 as $k=>$v)
$newArr[$v] = $arr2[$k];
Or check out array_combine
as the other poster mentioned. PHP has some good array functions like that and its always good to use them.
Once you have the array in this format
['Age'] => 45
['Weight'] => 90
['Arms'] => 2
You can print them the way you want as follows
foreach($newArr as $k=>$v)
echo "$k: $v "
Upvotes: 0
Reputation: 145482
I would propose that you first merge the two arrays into one associative array:
$assoc = array_combine($keys_array1, $num_array2);
Then it's just a matter of looping over that to generate the output string:
$str = "";
foreach ($assoc as $key=>$num) {
$str .= "$key,$num,";
}
Should the trailing ,
be an issue (you didn't say), then I would resort to a $str = rtrim($str, ",")
workaround afterwards.
Upvotes: 5