Reading data from a Json with php

Asked

Viewed 472 times

1

Good I get the following JSON via post:

string '{
"pedidos": [{
    "feito_data": "2017-08-07",
    "valor": 40.0
}]
}' (length=265)

With php I handle the data like this:

// Recebe dados do JSON
$mix = filter_input(INPUT_POST, 'json', FILTER_DEFAULT);

// Decodifica json
$jsonObj = json_decode($mix);

// Faz o parsing da string, criando o array
$mix = $jsonObj->pedidos;

// Navega pelos elementos do array, e cadastra novos clientes
foreach ($mix as $c) {

    echo $c->feito_data;
}

Well what I want to do is this, as json will only send me 1 result I don’t need to use the foreach and I don’t need to name the object as pedidos.

My question is how to receive the data so $c->feito_data?

  • Did a var_dump on $here I put the post with json to make sure the data came as you’re imagining ?

  • I will now edit the question ok.

  • I’m sure the $aqui It’s coming bad, I took the test now here, and everything looks right.

  • Syntax is correct, but really the return of $here must be wrong.

  • I don’t understand the problem, if you’re gonna use the foreach just one echo $c to print the value.

  • What is the return of var_dump($mix)?

  • How do I not need to put a name on the son? like $mix = $jsonObj->pedidos;

  • @Marcelodeandrade already added the return in the question.

  • You want to catch only the first occurrence of feito_data? For your key pedidos is an array.

  • That’s right my key pedidos is an array, but will always contain only 1 result, I want to get the value without needing theforeach

  • 2

    Just take it this way: $feitoData = $jsonObj->pedidos[0]->feito_data or change your json so that it always returns an object without being inside the array.

  • 1

    @Diegoschmidt vlw misses exactly what I wanted.

Show 7 more comments

2 answers

4


If you want to get only the first occurrence, you can access the index of the first element of array:

echo $jsonObj->pedidos[0]->feito_data;

As the key pedidos is a array, you will need to iterate on it to access other records.

@Edit

You can also use the function reset, which will point to the first element of array, being as follows:

reset($jsonObject->pedidos)->feito_data

See working on ideone

3

Your key pedidos is an array, so I understand it will only contain 1 element so it only accesses 1 element

$jsonObj->pedidos[0]->feito_data;

Browser other questions tagged

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