Foreach array and create a name for array with same ID

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'),
     );

By doing a foreach of these array, so the array with equal teamID will show an echo in the foreach of group 1, the others id equals group 2, etc.

    
asked by anonymous 22.04.2018 / 20:39

1 answer

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

The result will look like this:

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

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

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