How to merge/combine two values into single key in

2019-05-11 23:40发布

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.

2条回答
别忘想泡老子
2楼-- · 2019-05-12 00:21

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.

查看更多
神经病院院长
3楼-- · 2019-05-12 00:29

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

查看更多
登录 后发表回答