Php 从数组中获取重复下一个值的计数,并将其存储到其他数组中
我真的对这个逻辑感到困惑,似乎我无法理解,基本上我想要的是存储count,如果下一个元素和下一个元素中有相同的值,则将其存储在数组中,然后存储在其余的存储中 这是我的密码Php 从数组中获取重复下一个值的计数,并将其存储到其他数组中,php,arrays,Php,Arrays,我真的对这个逻辑感到困惑,似乎我无法理解,基本上我想要的是存储count,如果下一个元素和下一个元素中有相同的值,则将其存储在数组中,然后存储在其余的存储中 这是我的密码 $json = '[{ "fight_declaration": "1" }, { "fight_declaration": "2" },
$json = '[{
"fight_declaration": "1"
},
{
"fight_declaration": "2"
},
{
"fight_declaration": "2"
},
{
"fight_declaration": "1"
},
{
"fight_declaration": "3"
}
]';
$data = json_decode($json,true);
$count = 0;
$array = [];
while ($current = current($data) )
{
$next = next($data);
if (false !== $next && $next['fight_declaration'] == $current['fight_declaration'])
{
$count++;
$array[]['count'] = $count;
}
}
print_r($count);
我想要的输出是这样的
[{
"count": 1
},
{
"count": 2
},
{
"count": 1
},
{
"count": 1
}
]
在我的输出中,我希望fight_声明具有相同的值,现在我希望对其进行计数并将其存储在数组中
谢谢您可以这样做:
$counts = [];
foreach ($data as $entry) {
if (!isset($previous)) {
$currentCount = ['count' => 1];
} elseif ($entry->fight_declaration === $previous->fight_declaration) {
$currentCount['count']++;
} else {
$counts[] = $currentCount;
$currentCount = ['count' => 1];
}
$previous = $entry;
}
if (isset($currentCount)) {
$counts[] = $currentCount;
}
这基本上将当前计数存储在$currentCount
中,并且:
- 如果它是第一个值,则将其设置为1
- 如果与上一个相同,则增加该值
- 将其添加到计数列表中,否则将其重置为1
- 将最后一次计数存储到末尾的列表中