Mihai Mihai - 1 month ago 5
PHP Question

Dynamically transform simple array to multidimensional array in PHP

I have an array with contry list 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"}
}}

Answer Source

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

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

    $newArray = array();

    foreach($array as $key => $value) {
        array_push($newArray, array("code" => $key, "name" => $value));
    }

    var_dump($newArray);
?>