Foreach array and create a name for array with same ID

Asked

Viewed 226 times

0

Good idea and create groups of arrays with example names,

$arrays = 
array(
       array( 'teamID' => '1151', 'username' => 'iLilithZ'),
       array( 'teamID' => '1111', 'username' => 'iLilithZ'),
       array( 'teamID' => '1151', 'username' => 'iLilithZ'),
       array( 'teamID' => '1111', 'username' => 'iLilithZ'),
       array( 'teamID' => '0', '   username' => 'iLilithZ'),
     );

making a foreach of this array, so the equal teamID array shows an echo in group 1 foreach, the other equal id group 2, etc.

  • I don’t understand very well, you want to sort the array by group id?

  • no, example, I read a json and return it in array, hence I do a foreach of it, when it is part of a group teamID has the group id, can have more than 1 group in the same foreach, so I wanted what type, if the id 25 does not exist, say that it is group 1 hence another id 25, is part of group 1 also, the example of use is equal to that of this site, http://paladins.guru/match/pc/232442401

1 answer

0

$result = [];
foreach ($arrays as $key => $row) {
    $result[$row['teamID']][] = $row['username'];
}

The result will be like this:

array(
    1151 => array(
        "iLilithZ",
        "iLilithZ",
    ),
    1111 => array(
        "iLilithZ",
        "iLilithZ",
    ),
    0 => array(
        "iLilithZ"
    )
)

Then you go through this new organized array printing as follows:

$count = 1;
foreach ($result as $group) {
    echo 'Grupo '.$count++.PHP_EOL;
    foreach ($group as $player) {
        echo $player.PHP_EOL;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.