我的情况是这样的:
$array1 = array(
array(
'HotelNo' => '1',
'HCode' => 'IDJOG_00108',
'Name' => 'Dafam Merapi Merbabu',
'RmGrade' => 'Deluxe',
'TotalRate' => '1035'
),
array(
'HotelNo' => '4',
'HCode' => 'IDJOG_00110',
'Name' => 'Desa Puri',
'RmGrade' => 'Standard',
'TotalRate' => '427'
)
);
$array2 = array(
array(
'HotelCode' => 'IDJOG_00108',
'HotelName' => 'Dafam Merapi Merbabu',
'Phone' => '62 0274 4332772',
'Address' => 'jl. Seturan Raya Yogyakarta'
),
array(
'HotelCode' => 'IDJOG_00110',
'HotelName' => 'Desa Puri',
'Phone' => '0274 - 371225',
'Address' => 'Jl. Gedung Kuning No. 118'
),
array(
'HotelCode' => 'IDJOG_00111',
'HotelName' => 'Pyrenees-Yog',
'Phone' => '+62 274 543299',
'Address' => 'Jl.Sosrowijayan No.1'
)
);
我想结合$ array1和$ array2
我想要这样的输出:
IDJOG_00108
Dafam Merapi Merbabu
豪华
1035
JL。 Seturan Raya Yogyakarta
62 0274 4332772
IDJOG_00110
Desa Puri
标准
427
JL。 Gedung Kuning No. 118
0274 - 371225
我只能这样做:
foreach($array1 as $key=>$value){
echo $value['HCode'].'<br>';
echo $value['Name'].'<br>';
echo $value['RmGrade'].'<br>';
echo $value['TotalRate'].'<br>';
echo '<br><br>';
}
如何以正确的方式组合两个阵列?
任何帮助非常感谢
干杯
答案 0 :(得分:1)
试试这个:
dnf install @development-tools
阐释:
$ array1和$ array2通过'HCode'和'HotelCode'键连接,所以你需要首先迭代$ array1,然后$ array2并检查$ array1 ['HCode'] == $ array2 ['HotelCode'],最后打印内容。
答案 1 :(得分:0)
这样的事情,但这是一个糟糕的解决方案:
function combine($array1, $array2) {
$result = array();
foreach ($array1 as $key1=>$val1) {
foreach ($array2 as $key2=>$val2) {
if (strcmp($val1['HCode'], $val2['HotelCode']) == 0) {
// we're here coz we've found additional info in array2
// remove unnecessary items
unset($val2['HotelCode'], $val2['HotelName']);
$result[] = array_merge($val1, $val2);
// remove item from array2
unset($array2[$key2]);
// assuming we have only one corresponding item in array2
break;
}
}
}
// if we don't need the rest of array2
// just change return to
// return $result;
return array_merge($result, $array2);
}
// get combined array
$final = combine($array1, $array2);
// do whatever we want
var_dump($final);
结果:
array(3) {
[0]=>
array(7) {
["HotelNo"]=>
string(1) "1"
["HCode"]=>
string(11) "IDJOG_00108"
["Name"]=>
string(20) "Dafam Merapi Merbabu"
["RmGrade"]=>
string(6) "Deluxe"
["TotalRate"]=>
string(4) "1035"
["Phone"]=>
string(15) "62 0274 4332772"
["Address"]=>
string(27) "jl. Seturan Raya Yogyakarta"
}
[1]=>
array(7) {
["HotelNo"]=>
string(1) "4"
["HCode"]=>
string(11) "IDJOG_00110"
["Name"]=>
string(9) "Desa Puri"
["RmGrade"]=>
string(8) "Standard"
["TotalRate"]=>
string(3) "427"
["Phone"]=>
string(13) "0274 - 371225"
["Address"]=>
string(25) "Jl. Gedung Kuning No. 118"
}
[2]=>
array(4) {
["HotelCode"]=>
string(11) "IDJOG_00111"
["HotelName"]=>
string(12) "Pyrenees-Yog"
["Phone"]=>
string(14) "+62 274 543299"
["Address"]=>
string(20) "Jl.Sosrowijayan No.1"
}
}