组合数组中重复索引的值

时间:2017-09-23 12:13:38

标签: php arrays

我需要组合重复索引的值。例如,我有以下数组:

Array
(
    [0] => Array
        (
            [0] => Player1
            [1] => 50
        )

    [1] => Array
        (
            [0] => Player2
            [1] => 10
        )

    [2] => Array
        (
            [0] => Player1
            [1] => 50
        )
)

Player1在数组中出现两次,因此我需要删除第二次出现,但将值50添加到第一次出现。像这样:

Array
(
    [0] => Array
        (
            [0] => Player1
            [1] => 100
        )

    [1] => Array
        (
            [0] => Player2
            [1] => 10
        )
)

我可以使用现有的PHP函数吗?

4 个答案:

答案 0 :(得分:0)

使用常规foreach循环和array_values函数:

$arr = [
    ['Player1', 50], ['Player2', 10], ['Player1', 50],
];

$result = [];
foreach ($arr as $item) {
    $k = $item[0];
    (isset($result[$k]))? $result[$k][1] += $item[1] : $result[$k] = $item;
}
$result = array_values($result);

print_r($result);

输出:

Array
(
    [0] => Array
        (
            [0] => Player1
            [1] => 100
        )

    [1] => Array
        (
            [0] => Player2
            [1] => 10
        )
)

答案 1 :(得分:0)

您可以尝试使用PHP in_array()函数来检查该元素是否存在

 if (in_array("Player1", $arrayname))
  {
  echo "Match found"; // do match and replace here
  }

答案 2 :(得分:0)

我觉得使用Playerequal()方法创建addPints()类可能是可行的方法。它将封装对象的比较

<?php
class Player {
    /** @var int **/
    private $points;

    /** @var string **/
    private $name;

    public function __construct(string $name, int $points) 
    {
        $this->name = $name;
        $this->points = $points;
    }

    public function equals(Player $player) : bool
    {
        return $this->name === $player->name();
    }

    public function name() : string 
    {
        return $this->name;
    }

    public function points() : int
    {
        return $this->points;
    }

    public function addPoints(int $points) : void
    {
        $this->points += $points;
    }
}

$a1 = [new Player("player1", 50), new Player("player2", 10), new Player("player1", 50)];

$result = [];

foreach ($a1 as $player) {
    $existing = false;

    foreach ($result as $player2) {
        if ($player2->equals($player)) {
            $player2->addPoints($player->points());
            $existing = true;
        }

    }

    if (!$existing) {
        $result[] = $player;
    }
}

var_dump($result);

答案 3 :(得分:0)

替代输出数组是让#34;播放器&#34;作为数组中的关键,值是得分 我发现这是一个更有效的阵列,更容易使用 而不是在每个玩家之前有一个通用号码 echo $arr[5][0]; // example "Player7"
然后你需要获得价值:
echo $arr[5][1]; // example "50" 这很难用 我的回答给你了 echo $arr["Player7"]; // "50"

此答案不符合预期结果,但可能对其他人有用。

$arr = [['Player1', 50], ['Player2', 10], ['Player1', 50]];

Foreach($arr as $subarray){
    // If player does not exist in result array add it with zero score.
    If(!isset($result[$subarray[0]])) $result[$subarray[0]]=0;

    // Add current player score to result array player score.
    $result[$subarray[0]] +=$subarray[1];
} 
Var_dump($result);

输出;

array(2) {
    ["Player1"]=> int(100)
    ["Player2"]=> int(10)
}