Change equal titles

1

I have foreach with equal results being printed, I need to change the ones that are the same.

An example of the code is this:

foreach ($courses as $key => $course) {
    var_dump($course->fullname);
}

Inside the foreach the result is this giving a var_dump($course->fullname);

string(6) "Nome 1" 
string(6) "Nome 2" 
string(6) "Nome 1"

This is var_dump($course);

array(3) 
    { [1]=> object(stdClass)#442 (1) { ["fullname"]=> string(6) "Nome 1" } 
    { [2]=> object(stdClass)#443 (1) { ["fullname"]=> string(6) "Nome 2" } 
    { [3]=> object(stdClass)#444 (1) { ["fullname"]=> string(6) "Nome 1" } 
}

How do I change the fullname of the same results?

    
asked by anonymous 03.11.2016 / 18:46

1 answer

1

You can do this:

<?php
$courses = array((object) array("fullname" => "Nome 1"), (object) array("fullname" => "Nome 2"), (object) array("fullname" => "Nome 2"), (object) array("fullname" => "Nome 1"), (object) array("fullname" => "Nome 1"), (object) array("fullname" => "Nome 2"));
$names = array(); // criamos um array vazio para guardar os nomes, que ficam como a key, e respetiva contagem

foreach($courses as $key => $course) {
    if(!isset($names[$course->fullname])) { // se o nome não existir ainda no nosso array
        $names[$course->fullname] = 0; // vamos iniciar a contagem do nome a 0 ex: $names['Nome 1'] = 0
    }
    $names[$course->fullname] += 1; // incrementamos 1 à contagem, quantas vezes aquele nome apareceu
    $courses[$key]->fullname = $course->fullname. ' - ' .$names[$course->fullname]; // criamos o nosso novo nome no array principal
}

Being $courses happens to be, making print_r($courses); :

Array ( [0] => stdClass Object ( [fullname] => Nome 1 - 1 ) [1] => stdClass Object ( [fullname] => Nome 2 - 1 ) [2] => stdClass Object ( [fullname] => Nome 2 - 2 ) [3] => stdClass Object ( [fullname] => Nome 1 - 2 ) [4] => stdClass Object ( [fullname] => Nome 1 - 3 ) [5] => stdClass Object ( [fullname] => Nome 2 - 3 ) )

DEMONSTRATION

    
03.11.2016 / 19:27