我不确定用于我的标题的适当术语是什么,但只是想知道在下面的解决方案需要在关联数组中合并/组合两个值。 例如,我有这个数组:
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
)
)
在此,我想将company_1
与address_1
合并。所以输出应该是这样的:
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
)
)
请有人帮我找出解决此问题的最简单方法。
答案 0 :(得分:4)
您需要遍历数组并修改原始数组的相应键。
foreach ($array as $key => $agent) {
$array[$key]['agent_address_1'] = $agent['agent_company_1'] . ', ' . $agent['agent_address_1'];
unset($array[$key]['agent_company_1']);
}
详细了解foreach控制结构及其如何循环遍历数组。
答案 1 :(得分:1)
您可以在代码中使用array_map()
,如下所示:
<?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);
输出:
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
)
)
阅读更多内容: