Search code examples
phparraysmultidimensional-arraygroupingsub-array

Group an array containing single-element associative rows by second level keys to form an associative array of indexed elements


I have an array, which contains data as follows:

[
    0 => ['www.google.com' => 'www.google.com/a'],
    1 => ['www.google.com' => 'www.google.com/a'],
    2 => ['www.test.com' => 'www.test.com'],
    5 => ['www.test.com' => 'www.test.com/c'],
]

I need to group all links for particular url like this:

Array (
 [www.google.com] => Array (
      [0] => www.google.com/a
      [1] => www.google.com/a
      )
 [www.test.com] => Array (
      [0] => www.test.com
      [1] => www.test.com/c
      )
  )

Solution

  • If we call the first array $domains.

    $groups = array();
    
    for ($i = 0; $i <= count($domains); $i++)
    {
        foreach ($domains[$i] as $domain => $url)
        {
             $groups[$domain][] = $url;
        }
    }
    
    print_r($groups);
    

    That might work...