Change equal titles

Asked

Viewed 56 times

1

I have a foreach with equal results being printed, I need to change those that are equal.

An example of the code is this:

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

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

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

That’s the 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 can I change fullname of equal results ?

  • You want to change the name for example Name1 which has two to another Name?

  • yes!!!!!!!!!!!!!!!!!!

  • Which name you want to change, there is a pattern, for example has 3 names equal 1 will get the same name and the other two ??

  • I will put a suffix in the names, example: "Name 1 - 1", "Name 1 - 2" for all equal, can have several...

1 answer

1


You can do it like 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
}

Whereas $courses becomes, doing 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

Browser other questions tagged

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