Reading data from a Json with php

1

Well I get the following JSON via post:

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

With php I treat 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 the following, as json will only send me 1 result I do not need to use foreach and I do not need to give a name to the object as pedidos .

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

    
asked by anonymous 07.08.2017 / 13:49

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;

Since the pedidos key is a array , you will have to iterate over it to access other records.

@edit

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

reset($jsonObject->pedidos)->feito_data

See working at ideone

    
07.08.2017 / 14:29
3

Your key pedidos is an array, so I understand it will only contain 1 element then it does the following access only the 1 element

$jsonObj->pedidos[0]->feito_data;
    
07.08.2017 / 14:29