Handle Json Array in PHP

Asked

Viewed 626 times

2

How do I get a particular item from a PHP array.

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) he returns:

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

and the var_dump($usr) returns NULL.

The Two echo() don’t show his name. How do I get this data?

  • the var dump($newUsers); brings an array: array(3) { [0]=> string(38) "{\"nome\":\"alvaro\",\"idade\":\"34\"}" [1]=> string(34) "{\"nome\":\"bia\",\"idade\":\"7\"}" [2]=> string(36) "{\"nome\":\"alice\",\"idade\":\"2\"}"}

  • 2

    I am using PHP 5.2. It seems that the problem is with my json_decode

  • I realized that in my var_dump($users) it brings a string string(38) before the array item "{\"nome\":\"alvaro\",\"idade\":\"34\"}"

1 answer

1


If your PHP version doesn’t have json_decode, do this without json_decode takes more work.

Assuming the array always has such data ("chave":"valor") should be able to use it 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 joined together \s in regex to allow sentences with spaces as well.

Phpfiddle: http://phpfiddle.org/main/code/ur56-1vrg

Browser other questions tagged

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