Reputation: 204
I´m trying to put JSON-Information into a PHP variable and I´m getting Errors all the time.
This is my Code to make the JSON readable:
header('Content-Type: application/json');
$jsondecode1 = json_decode($json1);
print_r ($jsondecode1);
This is a snippet of the $jsondecode1
:
Array
(
[0] => stdClass Object
(
[flightId] => ******
[******] => stdClass Object
(
[******] => ******
[******] => ******
[******] => ******
[******] => ******
[******] => ******
)
Notice: When I echo
the jsondecode1
it outputs this:
Array to string conversion in C:\xampp......\simpletest3.php on line 48
So I used print_r()
.
What I tried to put (for example) [flightId]
into a PHP Variable:
$jsondecode1 = json_decode($json1);
$jsondecode2 = $jsondecode1->flightId;
print_r ($jsondecode2);
Output: Notice: Trying to get property 'flightId' of non-object in C:.........\simpletest3.php on line 48
I tried some other codes too, but the Outputs were very similar and I don´t want to make my Question longer than it needs to be.
So, how do I put (for example) the [flightId]
into a PHP variable.
Edit:
Solution:
$jsondecode1 = json_decode($json1);
$jsondecode2 = $jsondecode1[0]->flightId;
print_r ($jsondecode2);
Or:
foreach ($jsondecode1 as $data) {
print_r($data->flightId);
}
Upvotes: 3
Views: 118
Reputation: 72269
You have to do it like below (what you shown)
$jsondecode1 = json_decode($json1);
$jsondecode2 = $jsondecode1[0]->flightId;
echo $jsondecode2;
But you have multi-dimensional-array,so do like below:-
$jsondecode1 = json_decode($json1);
foreach ($jsondecode1 as $jsondecode) {
echo $jsondecode->flightId; // here you can use echo $flightId = $jsondecode->flightId;
}
Upvotes: 2
Reputation: 5973
Your json contains an array of objects, not 1 object.
$jsondecode1 = json_decode($json1);
// loop through all objects in the array
foreach ($jsondecode1 as $data) {
print_r($data->flightId);
}
Or if you only want to have the first object of the array:
$jsondecode1 = json_decode($json1);
$jsondecode2 = $jsondecode1[0]->flightId;
print_r ($jsondecode2);
But then the question is why is the json an array and not a single object?
Also you can not simply echo or print out non-scalar types (like arrays or objects), for that you will have to use print_r
.
Upvotes: 2
Reputation: 16436
Your flightId
is inside one array whoch index is 0
. So you have to first access that array then you can get flightId
try below code:
$jsondecode1 = json_decode($json1);
$jsondecode2 = $jsondecode1[0]->flightId;
print_r ($jsondecode2);
Upvotes: 2