我有一个阵列district
,其中包含36个区,我正在取他们的总统和区域秘书。
$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"
)
);
答案 0 :(得分: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
并在一个数据库查询中获取组合的必要结果可能更有效。您仍然可以遍历结果以构建所需的输出数组。
答案 1 :(得分:0)
$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.
}