0

I have a problem to get the value from json data inside array when the data is more than one.

When my data only one like this:

$mydata='[{"firstName":"Ana","height":5.3}]';

I can just access the height of Ana by substring-ing it first and the decode it, like this:

$mydata= substr($mydata, 1, -1);

$obj = json_decode($mydata);
print $obj->{'height'};

The problem is when the data look like this:

$mydata='[{"firstName":"Ana","height":5.3},{"firstName":"Taylor","height":5.11}]';

How can I get the height of Ana?

print $obj->{0}->{'height'}; //doesn't work.

Please help. Thankyou in advance.

2 Answers 2

2

use json_decode

 $b_arr=json_decode($mydata,true);
 $b_arr[0]['height'];//0 is index for array
Sign up to request clarification or add additional context in comments.

Comments

1

You can convert with json_decode and iterate through your array to get your specific data:

<?php
$mydata='[{"firstName":"Ana","height":5.3},{"firstName":"George","height":7.3}]';
$json = json_decode($mydata, true);
foreach($json as $key => $value) {
    if($value['firstName'] == 'Ana') {
        echo $value['height'];
        break;
    }
}
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.