问题
I am not sure what is the appropriate terms to use for my title but just wondering to have below solution where need to merge/combine two values into one within a associative array. For example I have this array:
Array
(
[1] => Array
(
[agent_name_1] => Agent 1
[agent_phone_1] => 0123456
[agent_company_1] => My Company
[agent_email_1] => agent@yahoo.com
[agent_address_1] => United States
)
)
Here I would like to combine company_1 with address_1. So the output should be like this:
Array
(
[1] => Array
(
[agent_name_1] => Agent 1
[agent_phone_1] => 0123456
[agent_email_1] => agent@yahoo.com
[agent_address_1] => My Company, United States
)
)
Please someone help me to find out the easiest way to solve this issue.
回答1:
You would need to loop through the array and modify the corresponding key of the original array.
foreach ($array as $key => $agent) {
$array[$key]['agent_address_1'] = $agent['agent_company_1'] . ', ' . $agent['agent_address_1'];
unset($array[$key]['agent_company_1']);
}
Read more about the foreach control structure and how it loops through arrays.
回答2:
You can use array_map() in your code like this:
<?php
$MyArray[1] = array (
'agent_name_1' => 'Agent 1',
'agent_phone_1' => '0123456',
'agent_company_1' => 'My Company',
'agent_email_1' => 'agent@yahoo.com',
'agent_address_1' => 'United States'
);
$array = array_map(function($n) {$n['agent_address_1'] = $n['agent_company_1'] . ', ' . $n['agent_address_1']; unset($n['agent_company_1']); return $n;}, $MyArray);
print_r($array);
Output:
Array
(
[1] => Array
(
[agent_name_1] => Agent 1
[agent_phone_1] => 0123456
[agent_email_1] => agent@yahoo.com
[agent_address_1] => My Company, United States
)
)
Read more at:
http://php.net/array_map
来源:https://stackoverflow.com/questions/29505098/how-to-merge-combine-two-values-into-single-key-in-the-same-array