Convert associative array to indexed array with associative subarrays

不问归期 提交于 2019-12-13 10:41:46

问题


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"
    }
}

回答1:


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);
?>



回答2:


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);
}



回答3:


This is simple do like this

$array = array( array('code'=> "country1", 'name'=> "CountryOne"), array('code'=> "country2", 'name'=> "CountryTwo"));


来源:https://stackoverflow.com/questions/45819269/convert-associative-array-to-indexed-array-with-associative-subarrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!