Receiving Json array in PHP [duplicate]

2

I have the following code on the application side:

function enviaMensagem() { 
    var send = "http://appchat.host56.com/mensagem.php?jsoncallback=?";
$.post( send, {"table": [{"d":1, "p":1, "m": "1"},{"d":2, "p":2, "m": "2"},{"d":3, "p":3, "m": "3"}]}, function( data ) {}, "json");

}

On the server side I have the following code:

$jsonObj = json_decode($json, true);
$table = $jsonObj->table; 
foreach ( $table as $e ) { 
\aqui eu gravo o resultado em um BD
}

When I pass only one string, without having a table, I can handle it eg:   $.post( send, {"d":1, "p":1, "m": "1"}, function( data ) {}, "json"); , but passing a table not.

How do I get the data table[0]['d'] ?

Side of the application

<script>
    var newUsers = [];

            newUser = {};
            newUser['nome'] = 'alvaro';
            newUser['idade'] = '34';
            newUsers.push(JSON.stringify(newUser));

            newUser1 = {};
            newUser1['nome'] = 'bia';
            newUser1['idade'] = '7';
            newUsers.push(JSON.stringify(newUser1));

            newUser2 = {};
            newUser2['nome'] = 'alice';
            newUser2['idade'] = '2';
            newUsers.push(JSON.stringify(newUser2));

            $.ajax({
                url: "mensagem.php",
                type: "POST",
                data: {
                    'newUsers[]': newUsers
                },
                success: function () {

                },
                error: function () {

                }
            });

<\script>

On the server side of the php I have:

if (isset($_POST['newUsers'])) {
    $newUsers = $_POST['newUsers'];
    var_dump($newUsers);
    foreach ($newUsers as $user) {
        $usr = json_decode($user,false);
        var_dump($usr);
        echo($usr->nome);
    }
}
?>

In the first var_dump of $ newUsers it has the result: array(3) { [0]=> string(38) "{\"nome\":\"alvaro\",\"idade\":\"34\"}" [1]=> string(34) "{\"nome\":\"bia\",\"idade\":\"7\"}" [2]=> string(36) "{\"nome\":\"alice\",\"idade\":\"2\"}"} and in the second I have: NULLNULLNULL I do not know how to handle this.

    
asked by anonymous 14.11.2014 / 16:25

1 answer

2

Your problem is that you are requesting an associative array when you pass true to the second parameter of json_decode .

If you use json_decode($json, true) you must use $table = $jsonObj['table']; .

If you pass false to json_decode($json, false) you will receive an object and then $table = $jsonObj->table; will already work.

Example: link

    
14.11.2014 / 16:45