How to merge/combine two values into single key in the same array

邮差的信 提交于 2019-12-06 02:24:17

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!