Alvin Mactal Alvin Mactal - 14 hours ago 2
PHP Question

Group array by date and make set value as keys

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'
)

Answer

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: