0

I am trying to display single value from array of values. If I use print_r($arr) it shows this values

{
    "a": 14,
    "b": 3,
    "c": 61200,
    "d": [
        "2014-04-22 12:00:06",
        "2014-04-23 12:00:06",
        "2014-04-24 12:00:06"
    ]
}

But when I tried to use echo $arr->a and $arr['a']. It shows illegal string offset 'a'. How to get single value from array of values?

1
  • 1
    decode it to an array first? Commented Apr 22, 2014 at 12:20

5 Answers 5

2

looks like json so need decode first with json_decode()

$d = '{"a":14,"b":3,"c":61200,"d":["2014-04-22 12:00:06","2014-04-23 12:00:06","2014-04-24 12:00:06"]}';
$j = json_decode($d);
echo '<pre>';
print_r($j);
echo $j->a;
Sign up to request clarification or add additional context in comments.

Comments

1

Decode from JSON:

$v = json_decode('{
    "a": 14,
    "b": 3,
    "c": 61200,
    "d": [
        "2014-04-22 12:00:06",
        "2014-04-23 12:00:06",
        "2014-04-24 12:00:06"
    ]
}');

echo $v->a;

Comments

1

More information would be useful. What version of PHP are using? Are you using a web engine (Apache, Nginx, etc) or just command line? Correct me if I'm wrong but I am assuming your using json_decode and making an it an object.

$obj = json_decode('{"a":14,"b":3,"c":61200,"d":["2014-04-22 12:00:06","2014-04-23 12:00:06","2014-04-24 12:00:06"]}');
echo "Result: " . $obj->a;

Result: 14

This worked just fine in PHP Versions 5.3, 5.4, 5.5

Comments

1

Try this

$arr = json_decode($arr);
echo $arr->a

Comments

1

The input looks like JSON - try the following to parse the JSON data:

$json_string = '{
    "a": 14,
    "b": 3,
    "c": 61200,
    "d": [
        "2014-04-22 12:00:06",
        "2014-04-23 12:00:06",
        "2014-04-24 12:00:06"
    ]
}';

$vals = json_decode($json_string);

echo $vals->a;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.