Treat Json Array in PHP

2

How do I get an item from an array in PHP.

I have the following code:

<?php

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

If I give a var_dump($user) it returns:

string(38) "{\"nome\":\"alvaro\",\"idade\":\"34\"}"

and var_dump($usr) returns NULL .

The two echo() does not show the name. How do I get these data?

    
asked by anonymous 26.11.2014 / 14:02

1 answer

1

If your version of PHP does not have json_decode , doing so without json_decode gives more work.

Starting from the principle that the array always has data of this type ( "chave":"valor" ) must give to use like this:

foreach ($newUsers as $user) {
   preg_match_all('/(\w+)[^\w]*([\p{L}\d\s]+)/', $user, $partes, PREG_SET_ORDER);
   $nome = $partes[0][2];
   $idade = $partes[1][2];
   echo 'O nome é: '.$nome.', e a idade é: '.$idade.'<br/>';
}

Note: I've added \s to regex to allow phrases with spaces too.

PHPFiddle: link

    
26.11.2014 / 15:16