如何将关联数组与不同的键组合?

时间:2017-02-18 07:20:05

标签: php arrays laravel array-merge array-reduce

我正在尝试合并具有不同键的5个关联数组。这是在5个数组上使用数组合并后的结果

array_merge($bucketExlData1, $bucketExlData2, $bucketExlData3, $bucketExlData4, $bucketExlData5)

结果

array:5 [▼
  0 => array:1 [▼
    "Name" => "John Test"
  ]
  1 => array:1 [▼
    "Archived-On" => "2016-05-02 18:20:26"
  ]
  2 => array:8 [▼
    "Phone" => "2132918968"
    "DOB" => "1800-01-01 00:00:00"
    "Referred-By-Practice" => "-"
    "Referred-By-Provider" => "-"
    "Last-Scheduled-To-Practice" => "-"
    "Last-Scheduled-To-Provider" => "-"
    "Last-Scheduled-To-Location" => "-"
    "Last-Scheduled-Date-of-Service" => "-"
  ]
  3 => array:1 [▼
    "Archived-Reason" => "no-need-to-schedule"
  ]
  4 => array:1 [▼
    "Notes" => "done"
  ]
]

我想使这个数组像

array:5 [▼   
    "Name" => "John Test"
    "Archived-On" => "2016-05-02 18:20:26"
    "Phone" => "2132918968"
    "DOB" => "1800-01-01 00:00:00"
    "Referred-By-Practice" => "-"
    "Referred-By-Provider" => "-"
    "Last-Scheduled-To-Practice" => "-"
    "Last-Scheduled-To-Provider" => "-"
    "Last-Scheduled-To-Location" => "-"
    "Last-Scheduled-Date-of-Service" => "-"
    "Archived-Reason" => "no-need-to-schedule"
    "Notes" => "done"
]

2 个答案:

答案 0 :(得分:2)

我假设你的阵列是这样的

$arrayName = array(
    '0' => array("Name" => "John Test"),
    '1' => array("Archived-On" => "2016-05-02 18:20:26"),
    '2' => array(
           "Phone" => "2132918968",
        "DOB" => "1800-01-01 00:00:00",
        "Referred-By-Practice" => "-",
        "Referred-By-Provider" => "-",
        "Last-Scheduled-To-Practice" => "-",
        "Last-Scheduled-To-Provider" => "-",
        "Last-Scheduled-To-Location" => "-",
        "Last-Scheduled-Date-of-Service" => "-"
        )
    );

然后尝试array_reduce

$result = array_reduce($arrayName, 'array_merge', array());

<强>输出

Array ( 
    [Name] => John Test 
    [Archived-On] => 2016-05-02 18:20:26
    [Phone] => 2132918968 
    [DOB] => 1800-01-01 00:00:00 
    [Referred-By-Practice] => - 
    [Referred-By-Provider] => - 
    [Last-Scheduled-To-Practice] => - 
    [Last-Scheduled-To-Provider] => - 
    [Last-Scheduled-To-Location] => - 
    [Last-Scheduled-Date-of-Service] => - 
)

答案 1 :(得分:1)

再试一次

array_merge_recursive($bucketExlData1, [
    $bucketExlData2, 
    $bucketExlData3, 
    $bucketExlData4, 
    $bucketExlData5
]);

或者

array_merge_recursive(
    $bucketExlData1,
    $bucketExlData2, 
    $bucketExlData3, 
    $bucketExlData4, 
    $bucketExlData5
);

此处的功能定义:array_merge_recursive