0

Estoy iterando sobre muchos datos y necesito organizarlos en algún tipo de mapa multidimensional.

Los datos que necesito guardar en este proceso son: companyid,mes,montoTotal. Lo importante es que estos valores los pueda guardar en cada iteración, para que cuando venga otro valor con el mismo companyId y el mismo mes pueda tomar el que ya tiene seteado y sumar el nuevo.

He probado con struct pero no me sirve, ya que una vez agregado el elemento no puedo acceder a los valores por medio del companyId y mes como lo haría en php: (variable[companyId][mes] = variable[companyId][mes] + nuevoValor)

En este momento tengo esto, pero la llave del map solo soporta 1 registro:

var masterMatriz = map[string]map[string]string{}

for _, value := range *mysqlResult{

 date := explode("-", value.Adj_date)
 dateKey := date[0] + "-" + date[1]

 if val, exist := masterMatriz[value.Company_id][dateKey]; !exist {
   masterMatriz[value.Company_id] = map[string]string{
                        dateKey: totalInLocalCurrency_formated,
                    }
 }else{
     current := masterMatriz[value.Company_id][dateKey]
     masterMatriz[value.Company_id][dateKey] = current + totalInLocalCurrency_formated

}

}

El problema de mi código es que al ser string mi llave siempre guardará 1 fecha por cada llave de companyId.

1 respuesta 1

0

no estoy seguro si entendí tu pregunta.

Creo que lo que querés se puede solucionar con un struct el cual va a tener structs asosciados.

package main

type company struct {
    name       string
    otherValue string
    dates      map[string]date
}

type date struct {
    date    string
    value      float64
    otherValue string
}

func main() {

    masterMatriz := make(map[string]company)
    dates := make(map[string]date)
    1234 := date{"1234", 111.0, "bla"}
    date["1234"] = 1234
    google := company{"google", "bla", dates}
    masterMatriz["google"] = google
    
    
    for _, value := range *mysqlResult {

        date := explode("-", value.Adj_date)
        dateKey := date[0] + "-" + date[1]
        
        company := masterMatriz[value.Company_id]
        
        if len(company) == 0 {
            masterMatriz[value.Company_id] = createNewCompany(value)
        }
        
        date := company[dateKey]
        
        if len(date) == 0 {
            company[dateKey] = createNewDate(value)
        }
        
        date.value = date.value + newValue

    }
}

Evidentemente vas a tener que crear los métodos createNewCompany y createNewDate pero incluí algunas lineas de ejemplo en el main para que veas como se inicializan estos structs.

Espero te sirva, saludos!

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.