Try this:
<?php
$messages = array(
'message1'=>array(
'type'=>'voice',
'call-id'=>'11',
'id'=>'message1'
),
'message2'=>array(
'type'=>'voice',
'call-id'=>'44',
'id'=>'message2'
),
'message3'=>array(
'type'=>'text',
'call-id'=>'44',
'id'=>'message3'
),
'message4'=>array(
'type'=>'text',
'call-id'=>'55',
'id'=>'message4'
),
'message5'=>array(
'type'=>'voice',
'call-id'=>'55',
'id'=>'message5'
),
);
$unique = [];
foreach ($messages as $value) {
if ($value['type'] == 'text') {
$unique[$value['call-id']] = $value;
// so text comes first and override any previous value with the same call-id
} else if (!array_key_exists($value['call-id'], $unique)) {
$unique[$value['call-id']] = $value;
// will be added only if no same call-id and will be overridden if same call-id with type text after
}
}
foreach ($unique as $value) {
$array[$value['id']] = $value;
}
echo '<pre>';
print_r($array);
OUTPUT:
Array
(
[message1] => Array
(
[type] => voice
[call-id] => 11
[id] => message1
)
[message3] => Array
(
[type] => text
[call-id] => 44
[id] => message3
)
[message4] => Array
(
[type] => text
[call-id] => 55
[id] => message4
)
)
3
solved Delete/unset an array element matching a key/value of another array element [PHP]