问题
I have a form that submits a report about checkpoints. Each checkpoint has a "status" and a "comment". The form is set up so it returns a multi-dimensional array with the key being the checkpoint ID like this:
array(3) {
["status"]=>
array(2) {
["000046"]=>
string(1) "S"
["000047"]=>
string(1) "S"
}
["comment"]=>
array(2) {
["000046"]=>
string(6) "Flarg."
["000047"]=>
string(0) ""
}
["submit"]=>
string(13) "SUBMIT REPORT"
}
In the above, checkpoint 000046 has a status of "S" and a comment of "Flarg."
What I'd like to do is create a new array, joining the two values together in a certain format, while preserving the keys. The endgame should look like this:
array(1) {
["000046"]=>
string(10) "S-'Flarg.'"
["000047"]=>
string(1) "S"
}
What is the most efficient way to go about doing this?.
回答1:
Given $array
and $array2
your two arrays
$result = array();
foreach( $array as $k=>$v ) {
$result[$k] = $v;
if (isset($array2[$k]))
$result[$k] .= '-' . $array2[$k];
}
print_r($result);
回答2:
There is no native PHP function to do this for you (which would be most efficient). Just loop through both arrays and start collecting.
A code example would be insulting so I've omitted it.
回答3:
Given $checkpoints
as the array
listed in your question, you could use:
$newCheckpoints = array();
foreach ($checkpoints['status'] as $k => $status) {
$newCheckpoints[$k] = $status . (!empty($checkpoints["comment"][$k]) ? "-'{$checkpoints['comment'][$k]}'" : '');
}
回答4:
First merge recursively arrays with statuses and comments, then glue both parts like that:
$output = array_merge_recursive($array['status'], $array['comment']);
array_walk($output, function (&$value, $key) { $value = empty($value[1]) ? $value[0] : $value[0]."-'".$value[1]."'"; });
But this will work only with PHP in version 5.3 or higher. To do the same in the lower version of PHP, you should create your function first and then pass its name:
function gluecomments(&$value, $key) { $value = empty($value[1]) ? $value[0] : $value[0]."-'".$value[1]."'"; }
$output = array_merge_recursive($array['status'], $array['comment']);
array_walk($output, 'gluecomments');
Proof:
For this input:
$array = array(
'status' => array(
'000046' => 'S',
'000047' => 'S',
),
'comment' => array(
'000046' => 'Flarg.',
'000047' => '',
),
'submit' => 'SUBMIT REPORT',
);
print_r($output)
printed the following:
Array
(
[000046] => S-'Flarg.'
[000047] => S
)
Which is probably what you wanted.
EDIT:
I have deleted checks, whether it is an array or not - I assume the variable is always in the format you have given to us, so this is not required.
来源:https://stackoverflow.com/questions/6316138/php-concatenating-array-values-into-a-new-array-given-two-arrays-with-identic