Pergunta

I have a key/value pair passed from Javascript via $.post as data : user_id.

I've brought it into PHP with $data = $_POST['data'] and when I vardump() that I get {"id":"1"}" as expected. However, I'd like to just access the value of 1.

How would I do that?

Foi útil?

Solução

It's just JSON. Use json_decode() to turn it into an object (or an array if you so choose) and then get the value of ID using standard object member variable access methods:

$data = json_decode($_POST['data']);
echo $data->id;

Demo

If you're using PHP 5.4+ (using array syntax and array dereferencing):

echo json_decode('{"id":"1"}', true)['id'];

Demo

Outras dicas

You can also try this:

$data = json_decode($_POST['data'], true)['id']
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top