转换 PHP 数组
Convert PHP array
我有 php 数组,例如:
['AL'=>'Albania','AD'=>'Andorra','AT'=>'Austria']
我需要把它转换成
[[code=>'AL',country=>'Albania'],[code=>'AD',country=>'Andorra'],[code=>'AT',country=>'Austria']].
如何在 php 中执行此操作?
这应该适合你:
<?php
$arr = ['AL'=>'Albania','AD'=>'Andorra','AT'=>'Austria'];
$result = array();
foreach($arr as $k => $v)
$result[] = array("code" => $k, "country" => $v);
print_r($result);
?>
输出:
Array ( [0] => Array ( [code] => AL [country] => Albania ) [1] => Array ( [code] => AD [country] => Andorra ) [2] => Array ( [code] => AT [country] => Austria ) )
PHP 脚本和您需要的输出表明您必须使用关联数组。这些数组允许在数组中使用命名键。您可以使用以下代码简单地获得所需的输出:
<?php
$a = ['AL'=>'Albania','AD'=>'Andorra','AT'=>'Austria'];//Associative Array Declaration
$output = array();
foreach($a as $w => $x)//For every value in $a, it will display code and the country
$output[] = array("code" => $w, "country" => $x);
print_r($output);//Displaying the array output
?>
我有 php 数组,例如:
['AL'=>'Albania','AD'=>'Andorra','AT'=>'Austria']
我需要把它转换成
[[code=>'AL',country=>'Albania'],[code=>'AD',country=>'Andorra'],[code=>'AT',country=>'Austria']].
如何在 php 中执行此操作?
这应该适合你:
<?php
$arr = ['AL'=>'Albania','AD'=>'Andorra','AT'=>'Austria'];
$result = array();
foreach($arr as $k => $v)
$result[] = array("code" => $k, "country" => $v);
print_r($result);
?>
输出:
Array ( [0] => Array ( [code] => AL [country] => Albania ) [1] => Array ( [code] => AD [country] => Andorra ) [2] => Array ( [code] => AT [country] => Austria ) )
PHP 脚本和您需要的输出表明您必须使用关联数组。这些数组允许在数组中使用命名键。您可以使用以下代码简单地获得所需的输出:
<?php
$a = ['AL'=>'Albania','AD'=>'Andorra','AT'=>'Austria'];//Associative Array Declaration
$output = array();
foreach($a as $w => $x)//For every value in $a, it will display code and the country
$output[] = array("code" => $w, "country" => $x);
print_r($output);//Displaying the array output
?>