Concatenate variable into array

Asked

Viewed 373 times

4

I have to requisition one json for a api, but I have to redeem data from a form to complement this json, the problem is that when rescuing the data into a variable I cannot put it in the correct way inside that json, I tried to concatenate in several 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":""

    }';
  • This array comes from where? are you mounting with PHP strings?

2 answers

4

You can turn your json in 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 like in the example:

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

1


When using simple quotes to concactnate you should use the point:

$var = 'variavel';

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

Which 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 experience the Heredoc, as in this reply by @Bacco, your code would look like this:

MEUJSON is optional, can change for any name, it’s 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

Browser other questions tagged

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