使用关联子数组将关联数组转换为索引数组 [英] Convert associative array to indexed array with associative subarrays

查看:210
本文介绍了使用关联子数组将关联数组转换为索引数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与国家数据类似的简单关联数组:

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

推荐答案

简单地循环通过它,并从每个键/值对创建一个新数组.

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

这篇关于使用关联子数组将关联数组转换为索引数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆