2013-07-18 50 views
0

我有一个在php(codeigniter)开发的网站,我想合并一些具有相同结构的数组。 这是我的数组的构造:合并复杂的数组php

$first = array(); 
$first['hotel'] = array(); 
$first['room'] = array(); 
$first['amenities'] = array(); 

/* 
Insert data into $first array 
*/ 

$second = array(); 
$second['hotel'] = array(); 
$second['room'] = array(); 
$second['amenities'] = array(); 

/* 
Insert data into $second array 
*/ 

后插入数据我想合并这个数组,但问题是,我在它里面子阵,我想创造一个独特的阵列那样:

$total = array(); 
$total['hotel'] = array(); 
$total['room'] = array(); 
$total['amenities'] = array(); 

这是尝试合并:

$total = array_merge((array)$first, (array)$second); 

在这阵我只有$第二阵列为什么呢?

+0

我对你想要的输出感到困惑 –

+0

想要的输出是像第一个r秒一样的数组,但是两个数组合并了@SamuelCook –

+0

你可以在找[array_merge_recursive()'](http:// php.net/manual/en/function.array-merge-recursive.php)? – complex857

回答

0

有这样做的没有标准的方式,你就必须这样做:

<?php 
$first = array(); 
$first['hotel'] = array('hello'); 
$first['room'] = array(); 
$first['amenities'] = array(); 

/* 
Insert data into $first array 
*/ 

$second = array(); 
$second['hotel'] = array('world'); 
$second['room'] = array(); 
$second['amenities'] = array(); 

$merged = array(); 
foreach($first as $key => $value) 
{ 
    $merged[$key] = array_merge($value, $second[$key]); 
} 

print_r($merged); 
+0

为什么在你不能确定稍后不需要时会覆盖'$ first'? –

0

好像array_merge不会做你认为它的作用:“如果输入数组具有相同字符串键,那么该键的后面的值将覆盖前一个键。“试试这个:

function merge_subarrays ($first, $second) 
    $result = array(); 
    foreach (array_keys($first) as $key) { 
    $result[$key] = array_merge($first[$key], $second[$key]); 
    }; 
    return $result; 
}; 

然后称其为:

$total = merge_subarrays($first, $second); 

,如果我理解正确你的问题,$total将包含你正在寻找的结果。