[英]Remove consecutive values in two dimensional array php
I have the following array below: 我下面有以下数组:
$array = array(
'90' => array (
'11:00' => array(
' dept' => 297
),
'11:01' => array(
'dept' => 297
),
'11:02' => array(
' dept' => 884
),
'11:03' => array(
'dept' => 297
),
),
'91' => array (
'11:00' => array(
'dept' => 297
),
'11:01' => array(
'dept' => 297
),
)
);
The 90 and 91 are userid. 90和91是用户ID。 Now inside the 90 and 91 key I want to remove the consecutive value, for example dept 297 it should return only once. 现在在90和91键中,我想删除连续值,例如dept 297,它应该只返回一次。 The output I want is: 我想要的输出是:
$array = array(
'90' => array (
'11:00' => array(
'dept' => 297
),
'11:02' => array(
' dept' => 884
),
'11:03' => array(
'dept' => 297
),
),
'91' => array (
'11:00' => array(
'dept' => 297
),
)
);
As you can see the dept id 297 returned only once. 如您所见,部门ID 297仅返回一次。
I tried the code below: 我尝试了下面的代码:
function filterSuccessiveDuplicates($array)
{
$result = array();
$lastValue = null;
foreach ($array as $arr =>$value){
$value = array_values($value);
foreach($value as $k => $v){
if ($v['dept'] !== $lastValue) {
$result[$arr][$k] = $v;
}
$lastValue = $v['dept'];
}
}
return $result;
}
print_r(filterSuccessiveDuplicates($array));
But its not working. 但是它不起作用。 The output is not what I want. 输出不是我想要的。 Any help? 有什么帮助吗?
You just needed to keep your $lastValue inside first loop.. And remove that array_values()
您只需要将$ lastValue保留在第一个循环中即可。然后删除该array_values()
function filterSuccessiveDuplicates($array)
{
$result = array();
foreach ($array as $arr =>$value){
$lastValue = null;
foreach($value as $k => $v){
if ($v['dept'] !== $lastValue) {
$result[$arr][$k] = $v;
}
$lastValue = $v['dept'];
}
}
return $result;
}
print_r(filterSuccessiveDuplicates($array));
I tested it.. It works well. 我测试了它。
Here is the output. 这是输出。
Array
(
[90] => Array
(
[11:01] => Array
(
[dept] => 297
)
[11:02] => Array
(
[ dept] => 884
)
[11:03] => Array
(
[dept] => 297
)
)
[91] => Array
(
[11:00] => Array
(
[dept] => 297
)
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.