How to build a JSON structure?

Asked

Viewed 973 times

1

I have the following JSON:

{
"status": true,
"msg": "",
"frete": [
    {
        "Transportadora": "Correios",
        "Tempo": "16",
        "Msg": "",
        "Codigo": "04510",
        "Servico": "PAC",
        "Valor": "131.30"
    },
    {
        "Transportadora": "Correios",
        "Tempo": "10",
        "Msg": "",
        "Codigo": "04014",
        "Servico": "Sedex",
        "Valor": "239.80"
    }
],
"embalagem": "60x32x28,7000"
}

How do I mount this json in PHP?

I have the following code:

function calculaFrete($cod_servico = null, $cep_origem, $cep_destino, $peso, $altura = '2', $largura = '11', $comprimento = '16', $valor_declarado = '0.50') {
$parametros = array();
$parametros['nCdEmpresa'] = '';
$parametros['sDsSenha'] = '';
$parametros['sCepOrigem'] = $cep_origem;
$parametros['sCepDestino'] = $cep_destino;
$parametros['nVlPeso'] = $peso;
$parametros['nCdFormato'] = '1';
$parametros['nVlComprimento'] = $comprimento;
$parametros['nVlAltura'] = $altura;
$parametros['nVlLargura'] = $largura;
$parametros['nVlDiametro'] = '0';
$parametros['sCdMaoPropria'] = 's';
$parametros['nVlValorDeclarado'] = $valor_declarado;
$parametros['sCdAvisoRecebimento'] = 'n';
$parametros['StrRetorno'] = 'xml';
$parametros['nCdServico'] = '04014,04510';
$parametros = http_build_query($parametros);
$url = 'http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx';
$curl = curl_init($url . '?' . $parametros);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$dados = curl_exec($curl);
$dados = simplexml_load_string($dados);

$json = array();
$json['status'] = true;
$json['msg'] = '';

foreach ($dados->cServico as $linhas) {

    if ($linhas->Erro == 0) {
        if ($linhas->Codigo == '04510'):
            $servico = 'PAC';
        elseif ($linhas->Codigo == '04014'):
            $servico = 'SEDEX';
        endif;

        $json['frete']['Transportadora'] = 'Correios';
        $json['frete']['Tempo'] = $linhas->PrazoEntrega;
        $json['frete']['Msg'] = '';
        $json['frete']['Codigo'] = $linhas->Codigo;
        $json['frete']['Servico'] = $servico;
        $json['frete']['Valor'] = $linhas->Valor;
    } else {
        echo $linhas->MsgErro;
    }
}
$json['embalagem'] = "60x32x28,7000";
echo json_encode($json);
}

calculaFrete(null, '40760170', '40760210', 7.000, 28, 32, 60, 35);

This PHP returns me this, totally different:

{"status":true,"msg":"","frete":{"Transportadora":"Correios","Tempo":{"0":"10"},"Msg":"","Codigo":{"0":"04510"},"Servico":"PAC","Valor":{"0":"35,85"}},"embalagem":"60x32x28,7000"}
  • Both json are valid, but RFC different. What’s the problem?

  • for example: did not give the loop, Pac and sedex and in the time code parameters, appears 0, and can not stay like this

2 answers

0


I solved the problem by doing it this way:

foreach ($dados->cServico as $linhas) {
    $linhas = (array) $linhas;
    if ($linhas['Erro'] == 0) {
        if ($linhas['Codigo'] == '04510'):
            $servico = 'PAC';
        elseif ($linhas['Codigo'] == '04014'):
            $servico = 'SEDEX';
        endif;

        $array[] = ['Transportadora' => 'Correios',
            'Tempo' => $linhas['PrazoEntrega'],
            'Msg' => '',
            'Codigo' => $linhas['Codigo'],
            'Servico' => $servico,
            'Valor' => $linhas['Valor']];
    } else {
        echo $linhas['MsgErro'];
    }
}
$json['frete'] = $array;
$json['embalagem'] = "60x32x28,7000";
echo json_encode($json, true);

-2

You are adding an object within the array, the is including the pointer in the assignment of your array, use the object cast for array on the lines you are assigning to the array $json['frete].

Follow the example:

$json['frete']['Transportadora'] = 'Correios';
$json['frete']['Tempo'] = (array) $linhas->PrazoEntrega;
$json['frete']['Msg'] = '';
$json['frete']['Codigo'] = (array) $linhas->Codigo;
$json['frete']['Servico'] = $servico;
$json['frete']['Valor'] = (array) $linhas->Valor;

See if that helps you.

  • yes, I’m using json_encode

  • Pablo, consider commenting on your own question to clear your doubts, I don’t see this as an answer.

  • I need the loop inside the freight array, I’ve really forgotten how to make this loop, and the answer, it doesn’t help what I want to do.

  • cast in the $json['freight assignment']['?']

Browser other questions tagged

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