我有以下多维数组:
$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'
),
);
我需要删除/取消设置例如$ messages [' message2'],因为还有另一个数组元素($ messages [' message3']),其中包含键和值(& #39;键入' =>' text',' call-id' =>' 44')。
基本上,如果我们有两个具有相同call-id的元素,则删除type = voice的元素。
因此,上面数组的结果应为:
$messages = 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'
),
);
答案 0 :(得分:0)
试试这个:
<?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);
输出:
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
)
)