0

I have the following multidimensional array in PHP.

For each array(), I have 3 informations for the example. IRL, I have more than 20.

Array
(
      [0] => Array
      (
            [date] => 2019-04-23
            [room] => 101
            [rate] => 10
      )
      [1] => Array
      (
            [date] => 2019-04-25
            [room] => 101
            [rate] => 10
      )
      [2] => Array
      (
            [date] => 2019-04-26
            [room] => 101
            [rate] => 10
      )
      [3] => Array
      (
            [date] => 2019-04-25
            [room] => 102
            [rate] => 12
      )
      [4] => Array
      (
            [date] => 2019-04-26
            [room] => 102
            [rate] => 12
      )
)

Is it possible to group datas from this array but only when the room and rate are similars ?


For example, the desire output from the previous array is the following:

Array
(
      [0] => Array
      (
            [room] => 101,
            [rate] => 10,
            [dates] => Array
            (
                [0] => 2019-04-23,
                [1] => 2019-04-25,
                [2] => 2019-04-26
            )              
      )
      [2] => Array
      (
            [room] => 102,
            [rate] => 12,
            [dates] => Array
            (
                [0] => 2019-04-25,
                [1] => 2019-04-26
            )
      )
)
Testy
  • 301
  • 2
  • 9
  • You can concat the room and rate and use as key - then loop the array and assign the dates. But this is only my way of doing it - what have you tried? – dWinder Apr 16 '19 at 03:04
  • Didn't you ask the same question an hour ago? – Barmar Apr 16 '19 at 03:27

1 Answers1

1

You could do with Array.reduce

Sandbox example

Code

<?php

$res  = array_reduce($you_array,function($acc,$val){
        $room = array_search($val['room'],array_column($acc,'room'));
        $rate = array_search($val['rate'],array_column($acc,'rate'));
    if($rate == $room && $room > -1){
        array_push($acc[$room]['date'],$val['date']);
    }else{
        $new_arr=$val;
        $new_arr['date']=[$val['date']];
        array_push($acc,$new_arr);
    }
    return $acc;
},[]);


print_r($res);
?>
prasanth
  • 22,145
  • 4
  • 29
  • 53
  • I super-do-not endorse this answer which is making iterated calls of `array_search()`, `array_column()`, and `array_push()`. All of these expenses can be eliminated. – mickmackusa Jun 26 '22 at 00:07