Concatenate variable in array

4

I have to request a json for a api , however I have to retrieve data from a form to complement this json , the problem is that by saving the data to a variable I can not put it Correct way within that json , I tried to concatenate it in different ways and the value is never passed correctly.

$str = '{
    "clienteLogin": 
    {
        "Token":"29b3bcbde41b48058bf410da09910849",
        "Operador":"",
        "IdUnidadeNegocio":8,
        "PalavraCaptcha":"",
        "nome": "$nome", //variavel 1
        "cadastro":"on",
        "Email": "$email" // variavel 2
    },
        "mesclarCarrinho":true,
        "Token":"29b3bcbde41b48058bf410da09910849",
        "IdUnidadeNegocio":8,
        "Operador":""

    }';
    
asked by anonymous 04.11.2017 / 20:28

2 answers

1

When using single quotation marks to concact you should use the dot:

$var = 'variavel';

echo 'foo ' . $var . ' bar';

That will result in:

foo variavel bar

So your code should look like this:

$str = '{
    "clienteLogin": 
    {
        "Token":"29b3bcbde41b48058bf410da09910849",
        "Operador":"",
        "IdUnidadeNegocio":8,
        "PalavraCaptcha":"",
        "nome": "' . $nome . '", //variavel 1
        "cadastro":"on",
        "Email": "' . $email . '" // variavel 2
    },
        "mesclarCarrinho":true,
        "Token":"29b3bcbde41b48058bf410da09910849",
        "IdUnidadeNegocio":8,
        "Operador":""

    }';

However you can try Heredoc, as in this @Bacco response, your code would look like this: / p>

  

MEUJSON is optional, you can change it by any name, just to make it easier

$texto = <<<MEUJSON
{
    "clienteLogin": 
    {
        "Token":"29b3bcbde41b48058bf410da09910849",
        "Operador":"",
        "IdUnidadeNegocio":8,
        "PalavraCaptcha":"",
        "nome": "$nome", //variavel 1
        "cadastro":"on",
        "Email": "$email" // variavel 2
    },
        "mesclarCarrinho":true,
        "Token":"29b3bcbde41b48058bf410da09910849",
        "IdUnidadeNegocio":8,
        "Operador":""

    }
MEUJSON;

Example in IDEONE

    
08.11.2017 / 17:05
4

You can turn your json into array , add whatever you want, and then convert to json again.

$jsonData = json_decode($json, true);
$jsonData['clienteLogin']['email'] = $email;
$jsonData['clienteLogin']['nome'] = $nome;

$completeData = json_encode($jsonData);

Or you can use some array functions as in the example:

$jsonData = json_decode($json, true);
$complete = array_merge($jsonData['clienteLogin'], ['nome' => $nome, 'email' => $email]);
$newJson = json_encode($complete);
    
04.11.2017 / 21:09