我正在尝试使用来自MySQL查询的foreach在循环内添加所有数据。数据包括键和值。但是在我的代码中,它在想要的数组之前用整数键括起来。
这是代码:
$count_get_airlines = $wpdb->get_var( "SELECT COUNT(*) FROM wp_shipping_airlines" );
foreach ($get_airlines as $airlines_data) {
$data[] = [$airlines_data->letter_code => $airlines_data->shipping_airline];
}
print_r($data);
结果如下:
Array (
[0] => Array ( [CA] => Air China )
[1] => Array ( [PX] => Air Niugini )
[2] => Array ( [OZ] => Asiana Airlines )
[3] => Array ( [CI] => China Airlines )
[4] => Array ( [MU] => China Eastern Airlines )
[5] => Array ( [CZ] => China Southern Airlines )
[6] => Array ( [ET] => Ethiopian Airlines )
[7] => Array ( [EY] => Etihad )
[8] => Array ( [BR] => Eva Air )
[9] => Array ( [GF] => Gulf Air )
[10] => Array ( [JL] => Japan Airlines )
[11] => Array ( [7C] => Jeju Air )
[12] => Array ( [KE] => Korean Airlines )
[13] => Array ( [KU] => Kuwait Airlines )
[14] => Array ( [MU] => Malaysian Airlines )
[15] => Array ( [WY] => Oman Air )
[16] => Array ( [QF] => Qantas Airlines )
[17] => Array ( [QR] => Qatar Airways )
[18] => Array ( [BI] => Royal Brunei )
[19] => Array ( [SV] => Saudia Airlines )
[20] => Array ( [TG] => Thai Airways )
[21] => Array ( [TR] => Tiger Airways )
[22] => Array ( [TK] => Turkish Airlines )
[23] => Array ( [UA] => United Airlines )
[24] => Array ( [MF] => Xiamen Airlines )
[25] => Array ( [PR] => Philippine Airlines )
[26] => Array ( [DL] => Delta Air Lines )
[27] => Array ( [CX] => Cathay Pacific Airways )
[28] => Array ( [SQ] => Singapore Airlines )
[29] => Array ( [NH] => All Nippon Airways )
[30] => Array ( [EA] => Emirates Airlines )
[31] => Array ( [AK] => AirAsia Phils. )
[32] => Array ( [5J] => Cebu Pacific )
);
我想要的是:
Array(
'CA'=> 'Air China (CA)',
'PX'=> 'Air Niugini (PX)',
'OZ'=> 'Asiana Airlines (OZ)',
'CI'=> 'China Airlines (CI)',
'MU'=> 'China Eastern Airlines (MU)',
'CZ'=> 'China Southern Airlines (CZ)',
'ET'=> 'Ethiopian Airlines (ET)',
'EY'=> 'Etihad (EY)',
'BR'=> 'Eva Air (BR)',
'GF'=> 'Gulf Air (GF)',
'JL'=> 'Japan Airlines (JL)',
'7C'=> 'Jeju Air (7C)',
'KE'=> 'Korean Airlines (KE)',
'KU'=> 'Kuwait Airlines (KU)',
'MU'=> 'Malaysian Airlines (MU)',
'WY'=> 'Oman Air (WY)',
'QF'=> 'Qantas Airlines (QF)',
'QR'=> 'Qatar Airways (QR)',
'BI'=> 'Royal Brunei (BI)',
'SV'=> 'Saudia Airlines (SV)',
'TG'=> 'Thai Airways (TG)',
'TR'=> 'Tiger Airways (TR)',
'TK'=> 'Turkish Airlines (TK)',
'UA'=> 'United Airlines (UA)',
'MF'=> 'Xiamen Airlines (MF)',
'PR' => 'Philippine Airlines (PR)',
'AK' => 'AirAsia Phils. (AK)',
'NH' => 'All Nippon Airways (NH)',
'CX' => 'Cathay Pacific Airways (CX)',
'5J' => 'Cebu Pacific (5J)',
'DL' => 'Delta Air Lines (DL)',
'EA' => 'Emirates Airlines (EA)',
'SQ' => 'Singapore Airlines (SQ)'
);
我想念什么?我究竟做错了什么?
非常感谢您的帮助。
谢谢!
-埃利
最佳答案
您需要设置键,而不是在数组内部创建新数组。
$count_get_airlines = $wpdb->get_var( "SELECT COUNT(*) FROM wp_shipping_airlines" );
$data =[];
foreach ($get_airlines as $airlines_data) {
$data[$airlines_data->letter_code] = $airlines_data->shipping_airline;
}
print_r($data);