我有一个简单的关联数组,其国家/地区数据如下:
$array = array('country1' => CountryOne, 'country2' => Country Two);
我如何动态将这个数组转换为多个数组,如:
array(2) {
[0] => array(2) {
["code"] => "country1", ["name"] => "CountryOne"
}
[1] => array(2) {
["code"] => "country2", ["name"] => "CountryTwo"
}
}
答案 0 :(得分:4)
只需loop通过它,并从每个键/值对创建一个新数组。
<?php
$array = array("country1" => "CountryOne", "country2" => "CountryTwo");
$newArray = array();
foreach($array as $key => $value) {
array_push($newArray, array("code" => $key, "name" => $value));
}
var_dump($newArray);
?>
答案 1 :(得分:2)
简单。迭代你的数组并用你在其中找到的东西填充另一个:
$dst_array = array();
foreach ($array as $k => $v) {
$dst_array[] = array('code' => $k, 'name' => $v);
}
答案 2 :(得分:-2)
这很简单就像这样
$array = array( array('code'=> "country1", 'name'=> "CountryOne"), array('code'=> "country2", 'name'=> "CountryTwo"));