如何在内部数组中存储数组值?

时间:2016-01-17 15:28:34

标签: php arrays

我有一些像这样的数组

$countries=array(country_id->val,country->val,city_id->val,city_name->val)

每个国家/地区可以有多个城市。现在我希望每个国家的城市都有这样的内部数组:

$country=array(country_id->val,country->val,

cities=>array((city_id->val,city_name->val)
,(city_id->val,city_name->val),
 (city_id->val,city_name->val))  

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

我更喜欢像这样单独为城市创建一个数组:

$cities = [
             [city_id->val, city_name->val],
             [city_id->val, city_name->val],
             [city_id->val, city_name->val]
          ];//these brackets represent array in php

为了便于编码,您可以尝试这样:

$country = array(country_id->val, country_name->val, city_id->val,city_name->val, $cities);

现在,您可以在一系列国家/地区中添加城市数组:

$countries = [
                [
                   country_id->val, 
                   country_name->val, 
                   [
                      city_id->val, 
                      city_name->val
                   ], //first city
                   [
                      city_id->val, 
                      city_name->val
                   ], //second city
                   [
                      city_id->val, 
                      city_name->val
                   ]  //third city
                ], //first country

                [  
                   country_id->val, 
                   country_name->val, 
                   [
                      city_id->val, 
                      city_name->val
                   ], //first city
                   [
                      city_id->val, 
                      city_name->val
                   ], //second city
                   [
                      city_id->val, 
                      city_name->val
                   ]  //third city
                ]  // second country
             ]; 

此外,如果您需要相互关联的国家和城市,也可以这样做:

class Managementbla::UserController < ApplicationController
class Managementpoke::UserController < ApplicationController
...
class Managementmultiple::UserController < ApplicationController

因此创建一个三维数组...

答案 1 :(得分:0)

我会创建这样的东西:

$countries = array(
                $country_id->val => array(
                                      "name" => $country_name->val
                                      "cities"=> array(
                                                   city_id->val=>city_name->val, 
                                                   city2_id->val=>city2_name->val)
                                     )
                );