【发布时间】:2021-12-03 19:16:00
【问题描述】:
我有一些代码可以从数组中的每个 url 中删除参数。 然后它为每个匹配的 url-keyword 求和一个分数,最后它应该从值“位置”中获取平均值。
Everythink 对我有用。但我认为有没有办法用一个循环来做到这一点?现在我使用两个循环。 其中之一为我总结了价值。然后我需要使用一个 foreach 并将我的值的总和除以我匹配的关键字 url 发生的次数。
也许有人知道如何在一个循环中计算平均“位置”分数?
<?php
$keywordsUrlsArray = array(
0 => array
(
'url' => 'https://www.example.pl/?test=19',
'keyword' => 'test',
'score1' => 100,
'score2' => 50,
'position' => 4
),
1 => array
(
'url' => 'https://www.example.pl/?test=2',
'keyword' => 'test',
'score1' => 100,
'score2' => 50,
'position' => 1
),
2 => array
(
'url' => 'https://www.example.pl/?test=3',
'keyword' => 'test',
'score1' => 100,
'score2' => 50,
'position' => 3
),
3 => array
(
'url' => 'https://www.example.pl/other-site?test=3',
'keyword' => 'test',
'score1' => 100,
'score2' => 50,
'position' => 3
)
);
并且有它的代码。
$res = array();
foreach ($keywordsUrlsArray as $urlResults) {
//remove params from url
$parsedUrl = parse_url($urlResults['url']);
$parsedUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . $parsedUrl['path'];
$keyword = $urlResults['keyword'];
if (array_key_exists($parsedUrl, $res)) {
//check if parsed url with removed parameters exists and if it has the same keyword I need to sum scores
if (isset($res[$parsedUrl][$keyword])) {
$res[$parsedUrl][$keyword]['urlCount'] += 1;
$res[$parsedUrl][$keyword]['score1'] += $urlResults['score1'];
$res[$parsedUrl][$keyword]['score2'] += $urlResults['score2'];
$res[$parsedUrl][$keyword]['position'] += $urlResults['position'];//my problem is there any way to compute my average position wtihout do a second foreach below?
continue;
}
}
$res[$parsedUrl][$keyword] = $urlResults;
$res[$parsedUrl][$keyword]['url'] = $parsedUrl;
$res[$parsedUrl][$keyword]['urlCount'] = 1;
}
//there I have to do a second foreach to compute average keyword/url position
//and compute position which will be sum of all positions divided by every matched keyword/url
$result = [];
foreach ($res as $k => $r) {
foreach ($r as $p => $t) {
$t['position'] = $t['position'] / $t['urlCount'];
unset($t['urlCount']);
$result[] = $t;
}
}
var_dump( $result);
return $result;
}
这就是我的结果。位置总和除以出现的 url。
array(2) {
[0]=>
array(5) {
["url"]=>
string(23) "https://www.example.pl/"
["keyword"]=>
string(4) "test"
["score1"]=>
int(300)
["score2"]=>
int(150)
["position"]=>
float(2.6666666666667)
}
[1]=>
array(5) {
["url"]=>
string(33) "https://www.example.pl/other-site"
["keyword"]=>
string(4) "test"
["score1"]=>
int(100)
["score2"]=>
int(50)
["position"]=>
int(3)
}
}
【问题讨论】: