Scroll through an array and separate the same names to make the appropriate changes

Asked

Viewed 339 times

-1

I need to scroll through an array that has the following elements:

$MeuArray = array("PEDRO" ,"PEDRO" ,"PEDRO" ,"PEDRO" ,"JOAO" ,"JOAO", "JOAO", "JOAO");

I need to separate by equal names, example: I want to take names that are equal to "PEDRO' to make the appropriate modifications then continue doing with the rest of the names.

How can I do that?

  • You want to leave the arrays unique, like leaving only one "PEDRO" array, or you want a comparison for all "PEDRO" array and play a value on them?

  • Next to these arrays there are other elements, such as: PEDRO Brasil 3242 3 PEDRO Brasil 8732 1 PEDRO Argentina 5423 2 because the same PEDRO has several records.

  • It’s unclear what you need... you mean you want to organize the array? 'Cause when you say "equal names" it’s not clear what you’re looking for.

  • I don’t think it would be appropriate for the same "Pedro" to have multiple criminal records. It would not be better to organize using an "ID", so you know which one is unique?

  • It is an old system, it was created this way. That’s why "PEDRO" has several registers.

1 answer

0

Well, if I understand you correctly, I believe that’s it, you can use a combination of for and if to know when to make the appropriate changes. Using your example:

$MeuArray = array("PEDRO" ,"PEDRO" ,"PEDRO" ,"PEDRO" ,"JOAO" ,"JOAO", "JOAO", "JOAO");

for ($i=0; $i <count($MeuArray) ; $i++) { 

    if($MeuArray[$i] == 'PEDRO')
    {
        // Faça aqui as devidas alterações para PEDRO
        // Podes criar um novvo array se desejar
        // Para utilizar o array atual $MeuArray[$i]['PEDRO'];
            echo "Teste";
        }
    }

And to get all the names, you would have to have an array with all the names, like the example you posted in $MeuArray.

Having this array, you can use the array_unique. For example:

$MeuArray = array("PEDRO" ,"PEDRO" ,"PEDRO" ,"PEDRO" ,"JOAO" ,"JOAO", "JOAO", "JOAO");
$result = array_unique($MeuArray);

The example will print:

Array
(
    [0] => PEDRO
    [1] => JOAO

)

Anything but talk.

Att;

  • And how could I make him play in another array the names that are equal, for example: he will go to read a file that has 100 names, but the same names are in order(PEDRO, PEDRO, PEDRO, JOAO, JOAO, JOAO, CARLOS, CARLOS, CARLOS) there as I do to differentiate the names? Because his example he has a simple thing, taking exactly the name PEDRO, ta made for this example. Thank you!

Browser other questions tagged

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