【问题标题】:Create Multidimensional array in codeigniter在codeigniter中创建多维数组
【发布时间】:2015-05-23 19:10:14
【问题描述】:

我有一个数组district,其中包含 36 个地区,我正在获取地区 ID 上的总裁和秘书。

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

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

视图的加载是:

$finalArray["result"]=$result;

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

所需的数组 但我想要一个这种形状的数组,即作为区名的键,以及带有联系方式的子数组

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

【问题讨论】:

  • $this->dashboard->get_contacts 得到了什么?以及在哪里取区名?

标签: php arrays codeigniter multidimensional-array


【解决方案1】:

您需要在$results 数组中设置正确的键。为此,您需要以下内容:

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
}

另外,假设您的get_contacts() 方法进行数据库查询,那么执行JOIN 并在一个数据库查询中获得组合的必要结果可能会更有效。您仍然可以遍历结果以构建所需的输出数组。

【讨论】:

    【解决方案2】:
    $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.
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多