I have a very simple problem that I unfortunately can't solve.
I use an API that returns an object that I convert to json to push it into my database, but I can't access the elements of this array (I don't know if it's multi-dimensional or not).
This is the json :
[
[
5.788894,
46.391834
],
[
5.788879,
46.392345
],
[
5.788877,
46.39241
]
]
And this this the object of the API :
API object
How should my loop be to retrieve the latitude and longitude of each point?
Thank you very much for your help;)
If I don't misunderstood your question and requirements then lets try like this way,
<?php
$json = '[[5.788894,46.391834],[5.788879,46.392345],[5.788877,46.39241]]';
$array = json_decode($json,1); // decode json to array
//just for debug
print '<pre>';
print_r($array);
print '<pre>';
foreach($array as $row){
echo "latitude = $row[0] and longitude = $row[1]".PHP_EOL;
}
DEMO: https://3v4l.org/U1F1n
Related
I am trying to access data from a JSON file, using PHP.
Here is what the JSON feed looks like:
[{
"performancesByDateDisplay":{
"2021-09-02":[{
"performanceId":10813388,
"performanceTime":"8:00 PM"
}],
"2021-09-03":[{
"performanceId":10813638,
"performanceTime":"8:00 PM"
}]
}
}]
And here is the code I am using to access the data:
foreach($json_output->performancesByDateDisplay as $events) {
$perfId = $events->performanceId;
}
But $perfId is not returning any value. I think it's because each array has a different "name" (for example "2021-09-02" in the first instance)? How do I access the data, without knowing in advance what this name will be (it's coming from an external json feed)?
Thanks!
Both the root of your JSON and each "$events" item is an array of objects, not just an object.
If you were to iterate each of these arrays for example, and access the objects inside one-by-one, you'd get the expected result:
foreach($json_output as $json_output_item){
foreach($json_output_item->performancesByDateDisplay as $events){
foreach($events as $event){
$perfId = $event->performanceId;
var_dump($perfId);
}
}
}
Output:
int(10813388)
int(10813638)
Did you forget to decode?
Well, first you need to decode the JSON data into a native PHP structure.
$decodedJson = json_decode($json_output, true);
Then you can access it just how you'll access a native PHP array and associative array. Notice the true, that's to decode the JSON string into an associative array. Also, it'd be better to just get inside the array while decoding, hence making the above statement:
$decodedJson = json_decode($json_output, true)[0];
Now you can iterate over it.
foreach($decodedJson as $events) {
foreach($events as $date => $event) {
$perfId = $event[0]['performanceId'];
}
}
I need to call this value registered in a MySQL column:
{"0":[{"Type":3,"Seconds":-185}],"1":[{"Type":4,"Seconds":-144}]}
With this form I get the JSON from the MySQL database:
$boosterResultant = $mysqli->query('SELECT boosters FROM player_equipment WHERE userId = '.$player['userId'].'')->fetch_assoc()['boosters']; //response: "{\"0\":[{\"Type\":3,\"Seconds\":-185}],\"1\":[{\"Type\":4,\"Seconds\":-144}]}"
I want to access what is in 'Seconds' to modify its value, so I use this form to modify it:
$boosterFinal = json_decode($boosterResultant,true);
$boosterFinal[0][0]['Seconds'] += 36000; //the value is changed successfully
echo "Output:", json_encode($boosterFinal); //out: [[{"Type":3,"Seconds":35815}],[{"Type":4,"Seconds":-144}]]
Since I run $boosterFinal = json_decode($boosterResultant,true); I get this: [[{"Type":3,"Seconds":-185}],[{"Type":4,"Seconds":-144}]]
but I need to stay like this for update later in the DB:
{"0":[{"Type":3,"Seconds":35815}],"1":[{"Type":4,"Seconds":-144}]} //good
//bad: [[{"Type":3,"Seconds":35815}],[{"Type":4,"Seconds":-144}]]
Edit: Thanks to #A. Cedano (link of answer in Spanish forum: here), I found the answer:
//This is the data that comes from the sample DB
$str='{"0":[{"Type":3,"Seconds":-185}],"1":[{"Type":4,"Seconds":-144}]}';
//Don't pass TRUE to json_decode to work as JSON as is
$mJson=json_decode($str);
$mJson->{0}[0]->Seconds+=36000;
//Object Test
echo $mJson; //Output: {"0":[{"Type":3,"Seconds":35815}],"1":[{"Type":4,"Seconds":-144}]}
If PHP sees that your array keys are ascending ints, it automatically converts them into an array (php.net/manual/en/function.json-encode.php)
You can disable this by passing the JSON_FORCE_OBJECT flag as a second param into json_encode: json_encode($boosterFinal, JSON_FORCE_OBJECT)
I had a similar problem, where JSON_FORCE_OBJECT didn't work. I had an array that looked like this:
<?php
$array = [
"someKey" => [
0 => "Some text....",
1 => "Some other text....."
]
];
Using json_encode with no flags I got a JSON object that looked like this:
{
"someKey": [
["Some text...."],
{"1": "Some other text....."}
]
}
This is clearly not what I had as the PHP object, and not what I want as the JSON object.
with the JSON_FORCE_OBJECT I got a JSON object that looked like this:
{
"someKey": [
{"0": "Some text...."},
{"1": "Some other text....."}
]
}
Which does fix the issuse I had, but causes another issue. It would add unnecessary keys to arrays that don't have keys. Like this:
$array = ["Sometext..."];
echo json_encode($array, JSON_PRETTY_PRINT|JSON_FORCE_OBJECT);
// {0: "Sometext..."}
We once again have the same issue, that the JSON object is not the same as the original PHP array.
Solution:
I used stdClass for the array that had numeric keys. and It encoded it to JSON correctly. code:
$array = [];
$stdClass = new stdClass();
$stdClass->{0} = "Some text...";
$stdClass->{1} = "Some other text....";
array_push($array, ["someKey" => $stdClass]);
$json = json_encode($array, JSON_PRETTY_PRINT);
echo $json;
//Output:
/*
{
"someKey": [
{"0": "Some text...."},
{"1": "Some other text....."}
]
}
*/
This is because PHP does not touch the indexes when encoding an stdClass.
I am working on an API in PHP that sends JSON data in form of an array to an android app. I'm having issues in returning the JSON array in the format;
"sammury" : [
{ "ClientName": "Samuel", "OrdersTaken": 400 },
{ "ClientName": "James", "OrdersTaken": 20 },
{ "ClientName": "Ritah", "OrdersTaken": 9 }
]
I'm using a php server online and a mysql database. I have added an image showing how the data that is returned loks like. Any Assistance Will be highly appreciated
Here is a simple example for you how to send your desired response.
1) Create your object arrays
2) Push the objects into the data array (you can use loop to push objects to array) and then assign that data array to the response array and convert it to Json.
Please see the working code here
$data = [];
$obj = [
"ClientName"=> "Samuel",
"OrdersTaken"=> 400
];
array_push($data, $obj);
$response = [
"sammury"=> $data
];
$json = json_encode($response);
echo $json;
I want to parse values from an Json API, but I cant get it to work
The API returns this JSON:
[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]
I tried to get the ID value like this:
$json_obj = json_decode($resp);
print $json_obj->assets[0]->id;
but I get no result whereas it should be 6. What do I do wrong here?
Remember the outer part of the JSON is an array, as suggested by the opening [. So you need to first access the first (and only) element of it:
$json_obj[0]->assets[0]->id; //<-- note the first [0]
I think the correct answer is
$json_obj = json_decode($resp);
print $json_obj[0]->assets[0]->id;
The json object will be converted to a php array, since you have an array with a object inside in your case it will be a multidimentional array with the objects inside.
Try this its worked for me..
$json ='[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]';
$json_obj = json_decode($json);
var_dump($json_obj[0]->assets[0]->id)
?>
decode JSON to the array and fetch the id by proper array keys
$jToArray = json_decode($resp, TRUE);
echo $jToArray[0]['assets'][0]['id'];//You will get the correct id
I am facing a strange issue with my PHP code (I'm a beginner to PHP so apologies for my bad coding skills). Each array item in my JSON has a unique ID associated with it, to delete an array I just pass the unique ID to my code and it deletes the array item associated with it, but all my array items contain an integer field and that doesn't get deleted and it messes up my JSON (parsing fails when I try to do so later).
<?php
$var1 = filter_input(INPUT_POST, 'unique_id', FILTER_UNSAFE_RAW);
if ($var1 === null) {
die('The "unique_id" parameter is not set');
}
$data = file_get_contents('feed.json');
if ($data === false) {
die('An error occurred when opening "feed.json"');
}
$json = json_decode($data, true);
if ( ! isset($json[0]['unique_id'])) {
die("The JSON was not decoded correctly");
}
foreach ($json as $key => $value) {
if ($value['unique_id'] == $var1) {
unset($json[$key]);
}
}
$new_json_string = json_encode($json);
file_put_contents('feed.json', $new_json_string, JSON_UNESCAPED_SLASHES | LOCK_EX);
echo "Success";
?>
Here's the sample JSON:
[
{"student_id":"22222222","unique_id":"862916786a1340afbfdf23caa541963f","status":"Hey yo what's up","image":"none","likes":"0"},
{"student_id":"33333333","unique_id":"d237556a90d44b1397e9290cd8g09349","status":"Message from another student","image":"none","likes":22}
]
after deleting, I'm left with
{"1":{"student_id":"33333333","unique_id":"d237556a90d44b1397e9290cd8g09349","status":"Message from another student","image":"","likes":31}
As you can see {"1": is invalid and shouldn't be there.
Does anyone know what am I doing wrong?
EDIT: Here's my code to create a new array item in my JSON
$json = file_get_contents('feed.json');
$data = json_decode($json);
$data[] = array('student_id' => "$student_id", 'unique_id' => "$unique_id" ,'status' => "$status_txt", 'image' => "$image_link", 'likes' => "0");
file_put_contents('feed.json', json_encode($data), JSON_UNESCAPED_SLASHES | LOCK_EX);
This is a combination of two things:
There is no representation of sparse Arrays in JSON
JSON's arrays with [] can only have a comma-separated list of contiguous elements starting from index 0.
No type information distinguishes JSON arrays and JSON objects in PHP
Both of these things are stored as PHP's array type. JSON objects use the associative keys.
When you unset index 0 from your array, it becomes sparse. Now, the only way to encode something that has a something[1] but no something[0] in JSON is to have an object with a key "1".
PHP's JSON encoder allows this because the array you pass in is of the right type (array) to be serialized as a JSON object. So it does this.
Maybe you wanted to use array_splice to remove the array element instead of unset.
Use array_values() to convert array as notified by Cheery in comments.