给定两个数组合并公用值

时间:2019-01-23 15:48:39

标签: php algorithm

$names = ['john','brian','john','steven','michael','paul','mark','paul','brian'];
$money = [2, 4, 3, 7, 5, 8, 20, -2, 4];

$names$money的索引相互对应。 我需要找到最有效的方法,将公用$money添加到每个$names并仅打印偶数。 例如,约翰出现了两次,分别有2和3钱。约翰斯只有5块钱。

所需的输出:

mark: 20
brian: 8
paul: 6

我正在考虑遍历每个数组,但这是O(n ^ 2)有没有更简单的方法?

4 个答案:

答案 0 :(得分:1)

对结果进行关联数组(哈希):

$names = ['john','brian','john','steven','michael','paul','mark','paul','brian'];
$money = [2, 4, 3, 7, 5, 8, 20, -2, 4];

$result = [];
for ($i = 0; $i < count($names); $i++) {
    if (!isset($result[$names[$i]])) {
        $result[$names[$i]] = 0;
    }
    $result[$names[$i]] += $money[$i];
}

arsort($result); // reverse (big first) sort by money 

print_r($result);

答案 1 :(得分:0)

只需遍历名称并使用它作为货币数组的键即可

$names = ['john','brian','john','steven','michael','paul','mark','paul','brian'];
$money = [2, 4, 3, 7, 5, 8, 20, -2, 4];

$res = [];
foreach ($names as $key => $value) {
    $res[$value] = isset($res[$value]) ? $res[$value] + $money[$key] : $money[$key];
}
var_dump($res);

答案 2 :(得分:0)

您只需要遍历$ names一次,并将name设置为结果变量的键。

$names = ['john','brian','john','steven','michael','paul','mark','paul','brian'];
$money = [2, 4, 3, 7, 5, 8, 20, -2, 4];

$data = [];
foreach ($names as $key => $name) {
    if (!isset($data[$name])) {
        $data[$name] = 0;
    }

    $data[$name] += $money[$key];
}

print_r($data);

答案 3 :(得分:0)

如果两个数组的大小相同,也许您需要检查。

$names = ['john','brian','john','steven','michael','paul','mark','paul','brian'];
$money = [2, 4, 3, 7, 5, 8, 20, -2, 4];

$result = [];

foreach ($names as $index => $name) {
    if (empty($result[$name]) {
        $result[$name] = $money[$index];
    } else {
        $result[$name] += $money[$index];
    }
}

print_r($result);