在foreach循环中,我的substr输出之后如何删除重复项?当前,它以倍数输出剥离的字符串。我希望输出只列出一个唯一的“ $ workername”,以避免重复出现
foreach ($block as $blocks) {
$worker = $block['pools']['snowgem']['workers'];
foreach($worker as $workers) {
//$workers = array_unique($workers);
$workername = substr($workers['name'], 0, strpos($workers['name'], "."));
echo $workername."<br>";
}
}
示例输出:
s1a5Ja3hPfP8FZgABzN8nYSU2uFgKetDTtL
s1a5Ja3hPfP8FZgABzN8nYSU2uFgKetDTtL
s1aKn13it5hsXHdUhFUXmp8f2Wj2tqo1CAi
s1aKn13it5hsXHdUhFUXmp8f2Wj2tqo1CAi
s1aKn13it5hsXHdUhFUXmp8f2Wj2tqo1CAi
s1aKn13it5hsXHdUhFUXmp8f2Wj2tqo1CAi
s1djunsw5pgbodthbrq9zGeEyKzDVvpSTEF
s1drJbyRARtXowrj4718TftHDo23RDPmKwr
s1dvGQ5d4pV4bhHBbfTUdvFHjgxgWtexm3d
s1fbJX6RRC4F4L3DxqXAKw8qmXmXw823vV1
s1hfcfXKP6vCBpAHyasEteVDrg3aQMgJZnA
s1hfcfXKP6vCBpAHyasEteVDrg3aQMgJZnA
s1hfcfXKP6vCBpAHyasEteVDrg3aQMgJZnA
转储:
Array
(
[pools] => Array
(
[snowgem] => Array
(
[workers] => Array
(
[s1a5Ja3hPfP8FZgABzN8nYSU2uFgKetDTtL.MESGOrig2] => Array
(
[name] => s1a5Ja3hPfP8FZgABzN8nYSU2uFgKetDTtL.MESGOrig2
[diff] => 35226
[shares] => 21.5
[invalidshares] => 0
[currRoundShares] => 12.9
[currRoundTime] => 53.843
[hashrate] => 307805989.547
[hashrateString] => 615.61 Sol/s
[luckDays] => 0.244
[luckHours] => 5.862
[paid] => 0
[balance] => 0
)
[s1aKn13it5hsXHdUhFUXmp8f2Wj2tqo1CAi.1060X4] => Array
(
[name] => s1aKn13it5hsXHdUhFUXmp8f2Wj2tqo1CAi.1060X4
[diff] => 986
[shares] => 3.57442495
[invalidshares] => 0
[currRoundShares] => 1.11351463
[currRoundTime] => 103.943
[hashrate] => 51173460.8742
[hashrateString] => 102.35 Sol/s
[luckDays] => 1.469
[luckHours] => 35.260
[paid] => 0
[balance] => 0
)
答案 0 :(得分:1)
使用数组存储输出的值,并检查是否已经输出了该值
$outputed_values = array();
foreach ($block as $blocks) {
$worker = $block['pools']['snowgem']['workers'];
foreach($worker as $workers) {
//$workers = array_unique($workers);
$workername = substr($workers['name'], 0, strpos($workers['name'], "."));
if (!in_array($workername, $outputed_values)){
echo $workername."<br>";
array_push($outputed_values, $workername);
}
}
}
答案 1 :(得分:0)
您已经在array_unique中使用了正确的功能。只需将您的子字符串存储在数组中,然后获取唯一值并输出即可。
foreach ($block as $blocks) {
$worker = $block['pools']['snowgem']['workers'];
foreach($worker as $workers) {
//$workers = array_unique($workers);
$workername = substr($workers['name'], 0, strpos($workers['name'], "."));
$name_array[] = $workername;
}
$name_array = array_unqiue($name_array);
echo "<pre>";
print_r($name_array);
echo "</pre>";
}
答案 2 :(得分:0)
似乎没有必要使用外部foreach循环,因为顶层只有一个键。您可以直接转到嵌套的“工人”键以获取工人。
$workers = $block['pools']['snowgem']['workers'];
然后,您可以在对格式重新格式化后从该数组获得的名称列表中使用array_unique
。
$unique_names = array_unique(array_map(function($worker) {
return substr($worker['name'], 0, strpos($worker['name'], "."));
}, $workers));