MikO
MikO

Reputation: 18741

Group 2d array data by one column and create a subarray in each group from another column

I was wondering if there's any PHP function (or an elegant combination of functions), similar to array_column, which allows to grouping this array by one column and pushing another column as children of the group?

$my_array = array(
  0 => array(
      'film_id' => '19'
      'showing_id' => '525'
  )
  1 => array(
      'film_id' => '117'
      'showing_id' => '507'
  )
  2 => array(
      'film_id' => '19'
      'showing_id' => '526'
  )
  3 => array(
      'film_id' => '117'
      'showing_id' => '510'
  )
)

Into this array (the keys now are the film_ids of the previous array, and the values are arrays containing all the showing_ids associated with each film_id):

$new_array = array(
  '19' => array(
      0 => '525'
      1 => '526'
  )
  '117 => array(
      0 => '507'
      1 => '510'
  )
)

Upvotes: 0

Views: 62

Answers (1)

BogdanD
BogdanD

Reputation: 175

You can try this:

$new_array = array();
foreach($my_array as $foo){
    $new_array[$foo['film_id']][] = $foo['showing_id'];
}

Upvotes: 1

Related Questions