Search code examples
phparrayscodeignitermultidimensional-arraygrouping

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"
    )
);

Solution

  • 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.