1

Bom dia amigos , em meus estudos com arrays me encontro num dilema , eu tenho um response que me devolve diversos produtos e nesses produtos temos a categoria e outras informações em JSON :

   Products: [
    {
    SKU: "xxxxxxx",
    SKUMain: "xxxxxxx",
    IsFreeRange: false,
    IsVirtual: false,
    IsDownloadable: false,
    ParentRechargeProduct: "",
    PriceUN: "23,00",
    RateADM: "0,00",
    Freight: "15,12",
    Handling: "1,68",
    PriceTotal: "39,80",
    Name: " xxxxx",
    Description: "descrição",
    Enable: true
    CategoryId: 13,
    Category: "ENTRETENIMENTO",
    },
    {
    SKU: "xxxxx",
    SKUMain: "xxxxxx",
    IsFreeRange: false,
    IsVirtual: false,
    IsDownloadable: false,
    ParentRechargeProduct: "",
    PriceUN: "17,00",
    RateADM: "0,00",
    Freight: "15,12",
    Handling: "1,68",
    PriceTotal: "33,80",
    Name: " CINÉPOLIS PADRÃO",
    Description: "descrição ",
    Enable: true,
    CategoryId: 13,
    Category: "ENTRETENIMENTO",
    },
    {
    SKU: "xxxxxxxxx",
    SKUMain: "xxxx",
    IsFreeRange: false,
    IsVirtual: false,
    IsDownloadable: false,
    ParentRechargeProduct: "",
    PriceUN: "100,00",
    RateADM: "8,00",
    Freight: "15,12",
    Handling: "1,68",
    PriceTotal: "124,80",
    Name: "xxxxxxx",
    Description: "descrição ",
    Enable: true,
    CategoryId: 8,
    Category: "RESTAURANTES",
    }]

pois bem , desenvolvi um código que captura a categoria e verifica se a index já existe no array e se existir incrementa a mesma, fazendo com que no final do processamento o código me devolva cada categoria e sua quantidade dentro do array products.

o código ultilizado em PHP foi este:

 $lista = json_decode($listaDeProdutos,true);
    $categorias = array('categoria'=>array());
    foreach($lista['Products'] as $pod){
        if(array_key_exists($pod['Category'], $categorias['categoria'])){
            $categorias['categoria'][$pod['Category']]['qtd']++;

        }else{
            $categorias['categoria'][$pod['Category']]['qtd'] = 1; 
        }

    }

   echo json_encode($categorias);

e minha resposta foi essa :

{
categoria: {
ENTRETENIMENTO: {
qtd: 10
},
RESTAURANTES: {
qtd: 11
},
DEPARTAMENTO: {
qtd: 69
},
SAÚDE E BELEZA: {
qtd: 20
},
MODA E ACESSÓRIOS: {
qtd: 33
},
HIPERMERCADOS: {
qtd: 94
},
COMBUSTÍVEL: {
qtd: 9
},
ARTIGOS ESPORTIVOS: {
qtd: 17
},
VINHOS: {
qtd: 14
},
VIAGENS: {
qtd: 10
},
GAMES: {
qtd: 5
},
BRINQUEDOS: {
qtd: 5
},
CASA E DECORAÇÃO: {
qtd: 5
},
CULTURA: {
qtd: 3
},
RECARGA: {
qtd: 25
},
PRÉ-PAGOS: {
qtd: 1
},
}
}

minha dúvida é se isso que fiz é uma boa prática ou existe algo mais robusto num problema parecido.

1
  • eu não vi problema...
    – novic
    19/02/2019 às 15:22

1 Resposta 1

0

Cara, ai depende do que você esta precisando. Se para utilizar é necessário criar um array dessa forma tudo bem. Você tem que pensar em como será utilizado no final e se dessa fora você irá conseguir interagir.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .