Biribu
Biribu

Reputation: 3823

How to parse second level of json php

I have a json like this:

[{"a":"1", "b":"2"},{"a":"4", "b":"5"},{"a":"15", "b":"2"}]

I want to get in php each row for update my database. I don't know the number of second level json are. Sometimes will be 1, sometimes 2 and sometimes more.

I thought, I could read it doing something like this:

$json = file_get_contents('php://input');
$json_post = json_decode($json, true);
$i = 0;

while(isset($json_post[$i])){
//Bla bla
$i++;
}

I have used many times json file in php but always, just one level. This is my first time with more than one. But I can't. I know, because I checked, that in $json I have the complete json file.

Upvotes: 0

Views: 1785

Answers (3)

BogdanM
BogdanM

Reputation: 635

$j = '[{"a":"1", "b":"2"},{"a":"4", "b":"5"},{"a":"15", "b":"2"}]';

$decoded = json_decode($j, true);
//var_dump($decoded);


foreach ($decoded as $key => $post) {
   $valueOfA = $post['a'];
   $valueOfB = $post['b'];
}

Upvotes: 1

Raggamuffin
Raggamuffin

Reputation: 1760

i'd use foreach:

foreach($json_post as $key => $value) {
    echo $value;
}

Upvotes: 1

brandonscript
brandonscript

Reputation: 72855

You need to reference the subkey in your array:

$json = file_get_contents('php://input');
$json_post = json_decode($json, true);
$i = 0;

while(isset($json_post[$i])){
    echo $json_post[$i]["a"];
    // or 
    echo $json_post[$i][0];
    $i++;
}

More docs can be found here: http://php.net/manual/en/language.types.array.php

And a similar question here: PHP reference specific key and value within multidimensional array

Upvotes: 4

Related Questions