Reputation: 105
I am trying to access decoded json elements that is in just one array, example:
[
{
timestamp: 1509523044,
tid: 83450451,
price: "6381.0",
amount: "1.0",
type: "sell"
},
{
timestamp: 1509523044,
tid: 83450448,
price: "6380.0",
amount: "1.12894377",
type: "buy"
}
]
I have tried
$json = json_decode($result);
echo $json[0]->price;
echo $json->[0]price;
echo $json->[0]->price;
Keep getting errors such as:
Fatal error: Cannot use object of type stdClass as array in
How can i acess each indivudal element with no array name? Thanks
Upvotes: 2
Views: 1029
Reputation: 27305
When you use json_decode
you get an object. If you need an array you have to set the second parameter to true
.
$json = json_decode($result, true);
Otherwise you have an object and you have to access all like an object. You can check that with var_dump($json);
. Generally it's better to work with the object version instead of the array version. But sometimes you need arrays.
Edit:
what i've written in the comment your json is not valid but with the original one you gave me it's working well.
var_dump(json_decode(file_get_contents('https://api.bitfinex.com/v1/trades/BTCUSD'), true));
with your example input it's working.
Upvotes: 1
Reputation: 23958
Because it's not a correct json you have to make it correct before decoding.
Here I use regex to replace the keys to "keys".
$str = ' [
{
timestamp: 1509523044,
tid: 83450451,
price: "6381.0",
amount: "1.0",
type: "sell"
},
{
timestamp: 1509523044,
tid: 83450448,
price: "6380.0",
amount: "1.12894377",
type: "buy"
}
]';
$json = json_decode(preg_replace('/(\w+):/', '"$1":', $str));
Echo $json[0]->price;
Upvotes: 0
Reputation: 260
Your json is malformed: in order to have a valid json you should have something like this:
<?php
$a = '[{
"timestamp": 1509523044,
"tid": 83450451,
"price": "6381.0",
"amount": "1.0",
"type": "sell"
},
{
"timestamp": 1509523044,
"tid": 83450448,
"price": "6380.0",
"amount": "1.12894377",
"type": "buy"
}
]';
$b = json_decode($a, true);
var_dump($b);
This will return the array you need
Upvotes: 4