0

I have an array like this

 0 => 
array (size=3)
  'datetime_read' => '2017-07-16 20:45:08'
  'parameter_name' =>  'Rainfall Amount'
  'reading' => '0.00'

 1 => 
array (size=3)
  'datetime_read' =>  '2017-07-16 20:45:08'
  'parameter_name' =>  'Rainfall Intensity'
  'reading' =>  '0.0'

2 => 
array (size=3)
  'datetime_read' => '2017-07-16 20:45:08' 
  'parameter_name' => 'Air Pressure' 
  'reading' =>  '77.45' 

and I need to group the data per date and get the values of parameter names and reading

 [0] => Array
        (
            'datetime_read' => '2017-07-16 20:45:08'
            'Rainfall Amount' => '0.00'
            'Rainfall Intensity' => '0.0'
            'Air Pressure' => '77.45'
        )
ibyte
  • 3
  • 5

2 Answers2

0

There are multiple ways to solve this problem. This is how I would solve it:

  1. Look for the array with the max size and write a loop that goes till that max value
  2. Initialize a new array outside the loop. This is going to be the final array
  3. Each time you traverse the loop, check the dates of all these arrays. If the date already exists in the new array, then simply add these parameters. Otherwise, you'll have to add the date too in the array.
alina
  • 291
  • 2
  • 9
0

Try this (assuming $input is your input):

$combined = array_reduce(
    $input,
    function (array $carry, array $item) {
        $datetimeRead = $item['datetime_read'];
        $parameterName = $item['parameter_name'];
        $reading = $item['reading'];

        $carry[$datetimeRead['datetime_read'] = $datetimeRead;
        $carry[$datetimeRead][$parameterName] = $reading;

        return $carry;
    },
    []
);

ksort($combined);

$data = array_values($combined);

For reference, see:

localheinz
  • 9,179
  • 2
  • 33
  • 44
  • Got it! Thanks for the answer! I encounter an error just a missing ")" in the function clause. – ibyte Jul 17 '17 at 09:23