如何将两个值合并/组合到同一数组中的单个键中 [英] How to merge/combine two values into single key in the same array

查看:153
本文介绍了如何将两个值合并/组合到同一数组中的单个键中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定要为我的标题使用什么合适的术语,但是只是想知道下面的解决方案需要在关联数组中将两个值合并/组合为一个值。
例如,我有以下数组:

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
    )

 )

在这里,我想将 company_1 address_1 结合起来。因此输出应如下所示:

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.

推荐答案

您需要遍历数组并进行修改

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']);
}

详细了解 foreach 控制结构及其在数组中的循环方式。

Read more about the foreach control structure and how it loops through arrays.

这篇关于如何将两个值合并/组合到同一数组中的单个键中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆