Search code examples
phparraysmultidimensional-arraygroupingsub-array

Group an array of objects by shared column values and create a subarray for a column where the values differ per group


Currently my array looks like:

array (size=3)
  0 => 
    object(stdClass)[32]
      public 'id' => string '11' (length=2)
      public 'housetype_id' => string '2' (length=1)
      public 'name' => string 'Test' (length=6)
      public 'excerpt' => string '' (length=0)
      public 'info_block_list_id' => string '1' (length=1)
  1 => 
    object(stdClass)[34]
      public 'id' => string '11' (length=2)
      public 'housetype_id' => string '2' (length=1)
      public 'name' => string 'Test' (length=6)
      public 'excerpt' => string '' (length=0)
      public 'info_block_list_id' => string '2' (length=1)
  2 => 
    object(stdClass)[35]
      public 'id' => string '11' (length=2)
      public 'housetype_id' => string '2' (length=1)
      public 'name' => string 'Test' (length=6)
      public 'excerpt' => string '' (length=0)
      public 'info_block_list_id' => string '3' (length=1)

Since only info_block_list_id changes I want to rearrange my array to look like so:

object(stdClass)[35]
  public 'id' => string '11' (length=2)
  public 'housetype_id' => string '2' (length=1)
  public 'name' => string 'Test' (length=6)
  public 'excerpt' => string '' (length=0)
  public 'info_block_list_id' => 
    array (size=3)
       0 => string '1' (length=1)
       1 => string '2' (length=1)
       2 => string '3' (length=1)

Solution

  • You want to create a variable that holds a hash/key of the unique id and changes to the info_block_list_id property to an array:

    $items =  [];
    foreach ($data as $item) {
        if (!isset($items[ $data->id ])) {
            $items[ $data->id ] = $item;
            $items[ $data->id ]->info_block_list_id = [];
        }
        $items[ $data->id ]->info_block_list_id[] = $item->info_block_list_id;
    }
    
    var_dump($items);