Muhammad Arslan Jamshaid
Muhammad Arslan Jamshaid

Reputation: 1195

Group query result set by 2 columns and create an associative array of associative arrays

I have an array district which contains 36 districts, and I am fetching their president & secretary on the district id.

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

Desired Array But I want an array of this shape, i.e. keys as district name, and sub arrays with contact details

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

Upvotes: 0

Views: 77

Answers (2)

André Silva
André Silva

Reputation: 1108

$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.
}

Upvotes: 0

jeroen
jeroen

Reputation: 91792

You need to set the correct key in your $results array. 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. You can still loop over the results to build the required output array.

Upvotes: 1

Related Questions