简体   繁体   中英

Not able to access JSON array in PHP

I am having trouble accessing information via PHP coming from json in javascript.

I use localstorage to save some temporary data:

var tbRomaneio = localStorage.getItem("tbRomaneio");// Recupera os dados armazenados
tbRomaneio = JSON.parse(tbRomaneio); // Converte string para objeto
if(tbRomaneio == null) { // Caso não haja conteúdo, iniciamos um vetor vazio
    tbRomaneio = new Array();
}

//Item
var medida = JSON.stringify({
    comprimento   : medidaComprimento,
    largura       : medidaLargura,
    token         : token.toString()
});
tbRomaneio.push(medida);
localStorage.setItem("tbRomaneio", JSON.stringify(tbRomaneio));

My code in javascript to post:

$.post('/pedido/salva-romaneio', {itens: localStorage.getItem("tbRomaneio")} )
.done(function(data) {
    //ok                                
})

So far so good. The problem is in PHP, when I read this information it returns error.

Here's my PHP code:

<?php
$itensRomaneio = json_decode($_POST['itens'], true);
print_r($itensRomaneio);
?>

Array
(
    [0] => {"comprimento":"230","largura":"54","token":"1495719950761"}
)

When I read the array I can not access the information, it gives the following error:

//Array
for($i = 0; $i < count($itensRomaneio); $i++) {

    echo $itensRomaneio[$i]->token;

}

Error:
<p>Severity: Notice</p>
<p>Message:  Trying to get property of non-object

And if I try to use it this way it only returns me this:

    //Array
    for($i = 0; $i < count($itensRomaneio); $i++) {

        echo $itensRomaneio[$i]['token'];

    }

Return only this:

" { "

If I give a print_r it is shown:

print_r($itensRomaneio[$i]);

//show
{"comprimento":"230","largura":"54","token":"1495719950761"}

What is going on?

You're calling JSON.stringify() on each medida before you push it onto the tbRomaneio array. So you need to decode each element.

foreach ($itensRomaneio as $iten) {
    $iten = json_decode($iten);
    echo $iten->token;
}

But a better solution is to not encode each item, just the whole array.

var medida = {
    comprimento   : medidaComprimento,
    largura       : medidaLargura,
    token         : token.toString()
};
tbRomaneio.push(medida);
localStorage.setItem("tbRomaneio", JSON.stringify(tbRomaneio));

Then in PHP, you should not use true as the second argument to json_decode() if you want to get an array of objects instead of associative arrays.

Try:

for($i = 0; $i < count($itensRomaneio); $i++) {

    $values = json_decode($itensRomaneio[$i]);

    echo $values->token;

}

You $itensRomaneio is an array of json string. You need to decode them before you access the token property.

array_walk($itensRomaneio, function($v) {
    echo json_decode($v)->token;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM