简体   繁体   English

在Codeigniter中创建多维数组

[英]Create Multidimensional array in codeigniter

I have an array district which contains 36 districts, and I am fetching their president & secretary on the district id. 我有一个包含36个区的数组district ,并且正在获取其区号上的总裁兼秘书。

$districts=$this->dashboard->get_districts();
foreach($districts AS $district)
    {
        $contacts=$this->dashboard->get_contacts($district["ID"]);

        $result=array_merge($result,$contacts);
    }

and loading of view is: 视图的加载是:

$finalArray["result"]=$result;

$this->load->view("admin/view_contacts.php",$finalArray);

Desired Array But I want an array of this shape, ie keys as district name, and sub arrays with contact details 所需的数组但是我想要这种形状的数组,例如,键作为地区名称,以及带有联系方式的子数组

$testarray=array(
            "Attock"=>array(
                "president"=>"gulzar",
                "secretary"=>"musa"
            ),
            "Bahawalnagar"=>array(
                "president"=>"muzamil",
                "secretary"=>"tania"
            )
        );

You need to set the correct key in your $results array. 您需要在$results数组中设置正确的密钥。 For that, you need something like: 为此,您需要以下内容:

foreach($districts AS $district)
{
  $result[$district['name']] = $this->dashboard->get_contacts($district["ID"]);
  //                 ^^^^ this is of course a guess and depends on your column name
}

Also, assuming that your get_contacts() method makes a database query, it might be more efficient to do a JOIN and get the combined necessary results in one database query. 另外,假设您的get_contacts()方法进行数据库查询,则执行JOIN并在一个数据库查询中获取组合的必要结果可能会更有效。 You can still loop over the results to build the required output array. 您仍然可以遍历结果以构建所需的输出数组。

$districts=$this->dashboard->get_districts();
$returnArray = array();
foreach($districts AS $district)
{
  $contacts=$this->dashboard->get_contacts($district["ID"]);
  $returnArray[$district['name']]['president'] = //Insert president value here.
  $returnArray[$district['name']]['secretary'] = //Insert secretary value here.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM