Php 在codeigniter中创建多维数组
我有一个包含36个地区的数组Php 在codeigniter中创建多维数组,php,arrays,codeigniter,multidimensional-array,Php,Arrays,Codeigniter,Multidimensional Array,我有一个包含36个地区的数组district,我正在根据地区id获取他们的总裁和秘书 $districts=$this->dashboard->get_districts(); foreach($districts AS $district) { $contacts=$this->dashboard->get_contacts($district["ID"]); $result=array_merge($result,$conta
district
,我正在根据地区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"
)
);
您需要在
$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
并在一个数据库查询中获得组合的必要结果可能更有效。您仍然可以循环结果以构建所需的输出数组。通过$this->dashboard->get_contacts获得什么?你的地区名称在哪里?
$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.
}