Assosiative and value order

Asked

Viewed 46 times

-1

People I have an associative array and would like to sort by single input with the sum of values. For example.

$product = ['Arroz branco' => 36,'Arroz parborizado' => 10, 'Arroz Integral' => 1, 'Açúcar' => 547, 'Açúcar refinado' => 10' , 'Feijao de corda' => 10, 'Feijão preto' => 15, 'FERMENTO' => 854];

The return should be:

$product = ['Arroz' => 47, 'Acucar' => 557, 'Feijao' => 25, 'Fermento' => 854 ];

I’m grateful for any help.

  • And what are the rules to define which are the same indexes? Always the first word? What if one is uppercase and the other lowercase?

  • Just the first word. I can already handle all the uppercase and minuscule put them all only with the first letter Uppercase.

  • And why "Sugar" became "Sugar"?

  • Retreat accentuation and cedilla.

  • Okay, have you tried anything? Do you have any idea how it can be done?

  • I’ve tried everything, but I always lose information when I format the indexes.

  • @Junioroliveira see my answer. I know the code got ugly,.

Show 2 more comments

1 answer

1


Hello.

Use the method strpos to compare if it is similar.

Solution

<?php
    $product = ['Arroz branco' => 36,'Arroz parborizado' => 10, 'Arroz Integral' => 1, 'Açúcar' => 547, 'Açúcar refinado' => 10 , 'Feijão de corda' => 10, 'Feijão preto' => 15, 'Fermento' => 854];
    $produto = ["Arroz" => 0,"Açúcar" => 0,"Feijão" => 0,"Fermento" => 0];
    foreach ($product as $key => $value) {
        if (strpos($key,"Arroz") !== false) {
            $produto["Arroz"] += $value;
        }
        if (strpos($key,"Açúcar") !== false) {
            $produto["Açúcar"] += $value;
        }
        if (strpos($key,"Feijão") !== false) {
            $produto["Feijão"] += $value;
        }
        if (strpos($key,"Fermento") !== false) {
            $produto["Fermento"] += $value;
        }
    }
    echo $produto["Arroz"];
    // 47
    echo $produto["Açúcar"];
    // 557
    echo $produto["Feijão"];
    // 25
    echo $produto["Fermento"];
    // 854
?>

Source

https://www.php.net/manual/en/function.strpos.php

I hope I’ve helped.

  • It makes sense yes. I used strpos but differently, it may be that your method gives the expected result. I can’t get a 1 in your answer why I started now

Browser other questions tagged

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