doubei2231
doubei2231
2017-08-22 13:39

使用关联子数组将关联数组转换为索引数组

已采纳

I have a simple associative array with country data like this:

$array = array('country1' => CountryOne, 'country2' => Country Two);

How can I dynamically transform this array in a multiple array like:

array(2) {
    [0] =>  array(2) {
        ["code"] => "country1", ["name"] => "CountryOne"
    }
    [1] => array(2) {
        ["code"] => "country2", ["name"] => "CountryTwo"
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongyong5912 dongyong5912 4年前

    Simply loop through it and create a new array from each key/value pair.

    <?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);
    ?>
    
    点赞 评论 复制链接分享
  • douchi8503 douchi8503 4年前

    Simple. Iterate through your array and fill another with what you find in it :

    $dst_array = array();
    foreach ($array as $k => $v) {
        $dst_array[] = array('code' => $k, 'name' => $v);
    }
    
    点赞 评论 复制链接分享
  • doujing5150 doujing5150 4年前

    This is simple do like this

    $array = array( array('code'=> "country1", 'name'=> "CountryOne"), array('code'=> "country2", 'name'=> "CountryTwo"));
    
    点赞 评论 复制链接分享

相关推荐