I have this array
$finalArray = array ( 0 => array ( 'deviceMacAddress' => 'd4:fc:9b:81:87:32', 'pressure' => 1015.12, 'temperature' => 22.296875, 'co2' => '', 'voc' => '', 'humidity' => '', 'light' => 1, 'pm1' => '', 'pm25' => '', 'pm10' => '', 'timestamp' => 1644917014994, ), 1 => array ( 'deviceMacAddress' => 'c8:7a:6c:09:eb:33', 'pressure' => '', 'temperature' => '', 'co2' => '20', 'voc' => '10', 'humidity' => '', 'light' => '50', 'pm1' => '', 'pm25' => '', 'pm10' => '', 'timestamp' => 1644917018996, ), 2 => array ( 'deviceMacAddress' => 'c8:7a:6c:09:eb:33', 'pressure' => '', 'temperature' => '', 'co2' => '10', 'voc' => '', 'humidity' => 32, 'light' => '', 'pm1' => '', 'pm25' => '', 'pm10' => '', 'timestamp' => 1644917018997, ), );
I want to get the unique array by deviceMacAddress from it. as you can notice there are two device with macAddress c8:7a:6c:09:eb:33 I can get the unique array easily . but i want to override the value if macaddress matches and get the latest one.
so i want my array to look like this
$finalArray = array ( 0 => array ( 'deviceMacAddress' => 'd4:fc:9b:81:87:32', 'pressure' => 1015.12, 'temperature' => 22.296875, 'co2' => '', 'voc' => '', 'humidity' => '', 'light' => 1, 'pm1' => '', 'pm25' => '', 'pm10' => '', 'timestamp' => 1644917014994, ), 1 => array ( 'deviceMacAddress' => 'c8:7a:6c:09:eb:33', 'pressure' => '', 'temperature' => '', 'co2' => '10', 'voc' => '10', 'humidity' => '32', 'light' => '50', 'pm1' => '', 'pm25' => '', 'pm10' => '', 'timestamp' => 1644917018997, ) );
Here I could get unique array https://3v4l.org/4UHYC
Advertisement
Answer
You are close. You will have to run another foreach inside the current foreach to check with empty values and skip them and override them if they are not.
Snippet:
<?php $data = []; foreach($finalArray as $value){ $data[ $value['deviceMacAddress'] ] = $data[ $value['deviceMacAddress'] ] ?? $value; foreach($value as $k => $v){ if($v == '') continue; $data[ $value['deviceMacAddress'] ][$k] = $v; } } print_r($data);