Herbs
Herbs

Reputation: 146

Combine sub-arrays of a multidimensional array when the first value of the sub-arrays are the same

I'm trying to merge sub-arrays which have the same date value

I haven't had much success with in_array() or array_merge().

My code is like this:

$lectureTimes = array (
  0 => 
  array (
    'CDate' => '2019-03-02',
    'a1' => '07:45',
    'a2' => '08:00',
  ),
  1 => 
  array (
    'CDate' => '2019-03-06',
    'b1' => '05:00',
    'b2' => '05:15',
  ),
  2 => 
  array (
    'CDate' => '2019-03-18',
    'c2' => '05:15',
    'c1' => '05:30',
  ),
  3 => 
  array (
    'CDate' => '2019-03-18',
    'd1' => '04:45',
    'd2' => '05:00',
  ),
)

This is the output I'm trying to get:

$lectureTimes = array (
  0 => 
  array (
    'CDate' => '2019-03-02',
    'a1' => '07:45',
    'a2' => '08:00',
  ),
  1 => 
  array (
    'CDate' => '2019-03-06',
    'b1' => '05:00',
    'b2' => '05:15',
  ),
  2 => 
  array (
    'CDate' => '2019-03-18',
    'c2' => '05:15',
    'c1' => '05:30',
    'd1' => '04:45',
    'd2' => '05:00',
  ),
)

For each CDate a new HTML table row is created.

Eventually I used JS on the client side to combine the duplicate rows but I'd prefer a full PHP solution.

Upvotes: 0

Views: 69

Answers (1)

kcm
kcm

Reputation: 1358

Since the "CDate" value is on the same level as the values, it is not possible to merge the values with a single method. You should iterate over the values to merge them. It could work with something like this:

$mergedLectureTimes = array();

foreach ($lectureTimes as $lectureTimeSet) {
    if(!isset($mergedLectureTimes[$lectureTimeSet['CDate']])) {
        $mergedLectureTimes[$lectureTimeSet['CDate']] = array();
    }
    $mergedLectureTimes[$lectureTimeSet['CDate']] = array_merge($mergedLectureTimes[$lectureTimeSet['CDate']], $lectureTimeSet);
}

var_dump($mergedLectureTimes);

Result:

array(3) {
  ["2019-03-02"]=>
  array(3) {
    ["CDate"]=>
    string(10) "2019-03-02"
    ["a1"]=>
    string(5) "07:45"
    ["a2"]=>
    string(5) "08:00"
  }
  ["2019-03-06"]=>
  array(3) {
    ["CDate"]=>
    string(10) "2019-03-06"
    ["b1"]=>
    string(5) "05:00"
    ["b2"]=>
    string(5) "05:15"
  }
  ["2019-03-18"]=>
  array(5) {
    ["CDate"]=>
    string(10) "2019-03-18"
    ["c2"]=>
    string(5) "05:15"
    ["c1"]=>
    string(5) "05:30"
    ["d1"]=>
    string(5) "04:45"
    ["d2"]=>
    string(5) "05:00"
  }
}

Upvotes: 2

Related Questions