This question already has answers here:
Append data to JSON array using PHP
(3 answers)
Closed 4 months ago.
I am trying to call array_push to add data sent via a GET request to my json array that holds registration ids for my GCM Clients
<?php
//read current regids
$myfile = fopen("regids.json", "r") or die("Unable to open file!");
$current_regids = fread($myfile,filesize("regids.json"));
// decode json
$decoded_json= json_decode($current_regids);
//save to php format array
$array = array($decoded_json);
//close file
fclose($myfile);
//get registration id
$regid = $_GET["regid"];
//push new reg id into array
array_push($array,$regid);
echo json_encode($array);
?>
The JSON should be as follows
["regid1","regid2", "regid3","regid4"]
However when I run the code it inorder to array_push "regid5" it gives me this
[["regid1","regid2","regid3","regid4"],"regid5"]
Its a major headache
You already get an array when you decode it:
// decode json
$decoded_json= json_decode($current_regids);
// now you have an array or object, depending on the input
// in your case it seems to be an array
And then you put the result in another array:
//save to php format array
$array = array($decoded_json);
So now you have a nested array.
You need to remove this line / use $decoded_json as the array you want to manipulate:
$array = array($decoded_json);
Note:- If you use array_push() to add one element to the array it's better to use $array[] = "value" because in that way there is no overhead of calling a function and it is also much faster and safer than array_push().
Related
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 8 months ago.
I have following php api to fetch some third party json data.
<?php
$url = 'https://players-facts-api.herokuapp.com/api/v1/resources/players?number=1'; // path to your JSON file
$imgUrl='https://random.cricket/players.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$dataImg= file_get_contents($imgUrl);
$characters = json_decode($data); // decode the JSON feed
$imgCharacters = json_decode($dataImg, true);
echo $characters[0]->fact;
echo $imgCharacters[0]->url;
print_r($imgCharacters);
?>
Here, when I run this php file, it gives me the correct output for
echo $characters[0]->fact;
But it kept giving me an error for the
echo $imgCharacters[0]->url;
The error is,
Warning: Attempt to read property "url" on null in C:\xampp\htdocs\cricinfo\player-fact-app\index.php on line 11
When I print the second array, it giving me something like follows,
Array ( [fileSizeBytes] => 285621 [url] => https://random.players/a62ccc75-2b8b-48d1-9110-b6e8d5687c07.jpg )
You parsed the second array as an associative array. There is no index 0, you can access the url using the key $imgCharacters['url']. (without -> as it is not an object)
This question already has answers here:
How to create a JSON object
(5 answers)
Closed 3 years ago.
I have the following PHP code, which gets executed when I hit the Submit button in a form:
// Save data
if(isset($_POST['save'])){
$newDataArr = array();
foreach ($data_array[0] as $k=>$v){
$newDataArr[] = array($k => $_POST[$k]);
}// ./ foreach
echo json_encode($newDataArr);
}
The echo I get is the following:
[{"ID->id":"esKZSCDfIC"},{"DT->createdAt":"2020-01-26T13:02:42"},{"DT->updatedAt":"2020-01-26T13:02:42"},{"ST->aString":"hey1"},{"NU->number":123},{"GPS->coords":["2.2222","44.4444"]},{"BL->aBool":false},{"AR->theArray":["xx","ww"]},{"FL->theFile":"https:\/\/xscoder.com\/xserver\/uploads\/6dydDtoTt5JjZzFc5L5V_image.jpg"},{"PO->userPointer":"vbN3b0C7bC"}]
Then I'll have to add that array into my JSON file as it follows:
$data = json_encode(array_values($newDataArr), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents('Test.json', $data);
But of course the syntax of my $newDataArr is not the right one, each JSON object must not be inside the { }, so this:
{"ID->id":"esKZSCDfIC"},
must become:
"ID->id":"esKZSCDfIC",
Is there a way to dynamically create a valid JSON array and push it to my Test.json file?
I've been through many posts on StackOverflow, but the result I get is always the same. I must use the PHP code above to get keys and values from my HTML inputs.
Instead of creating and pushing a new array on each iteration, set the values this way:
$newDataArr[$k] = $_POST[$k];
Hope this helps.
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
Some fields save data in the following way in one of my database field:
{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}
(* Don't know how it's called so i wrote string in the title)
How can i access data in particular for every "value".
One way could be to explode for every field but is there a better way to do this?
$ask_for_price_variable = [value from field];
if ($ask_for_price_variable == 'YES') {
// Do something
}
EDIT: As i said i did not know how it was called "JSON" so i could not search for it. Thank you all for the answers.
It is json data. You can access it using json_decode in php
$json = '{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}';
$data = json_decode($json,true);
$ask_for_price_variable = $data['ask_for_price_en-GB'];
Use json_decode
$str = '{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}';
print_r(json_decode($str, true));
You need to study about JSON type and how to encode or decode to get the data.
try this
echo "<pre>";
print_r( json_decode('{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}'));
to view the result , click run or hit f9, here
try json_decode function
$str = '{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}';
$data = json_decode($str, true);
print_r($data);
output:
Array ( [per_meter_en-GB] => TEST_FOR_TEST [roll_40_en-GB] => [ask_for_price_en-GB] => YES )
here you can access required value from $data array eg. echo $data['per_meter_en-GB']; will output TEST_FOR_TEST
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
So I've been stumped and I'm not sure how I would continue this
as an example let's just use books.com as the URL and let's say the JSON response from the URL is
[{"title":"first_title","description":"second_title"},
{"title":"second_title","description":"second_description"}]
How would I print all of the titles (just the titles) without knowing exactly how many there are.
I know that I would need to loop through the JSON but I'm unsure how, if I could have any guidance that would be fantastic.
You should get more familiar with json_decode() and foreach().
First you need to decode json (into array in this example) and then iterate through all elements.
Example of working code:
<?php
$json = '[{"title":"first_title","description":"second_title"},
{"title":"second_title","description":"second_description"}]';
$jsonArray = json_decode($json,true);
foreach($jsonArray as $entry) {
echo $entry['title'].'<br>';
}
Output:
first_title
second_title
This key is to actually convert the JSON response into a PHP associative array by using json_decode and then loop through it.
// Convert the JSON into a PHP associative Array
$response = json_decode($curlResponse,true);
// Loop through the array
foreach ($response as $value) {
echo $value['title'];
echo '<br/>';
}
How can I read a json array and add/merge a new element to it?
The content of my file data.json looks like this array:
[["2015-11-24 18:54:28",177],["2015-11-24 19:54:28",178]]
new element array example:
Array ( [0] => Array ( [0] => 2015-11-24 20:54:28 [1] => 177 ) )
I used explode() and file() but it failed (delimiter for index 1..)..
has someone another idea or it is the right way to solve?
Firstly you need to import JSON content to your application as a string what can be done with file_get_contents().
After that you have to decode--or "translate"--JSON format to PHP primitives via json_decode(). The result will be the expected array to be handled.
Then you may append a new item to that array using [] suffix eg. $a[] = $b;
These three steps are exemplified below.
// get raw json content
$json = file_get_contents('data.json');
// translate raw json to php array
$array = json_decode($json);
// insert a new item to the array
$array[] = array('2015-11-24 20:54:28', 177);
In order to update the original file you have to encode PHP primitives to JSON via json_encode() and can write the result to desired file via file_put_contents().
// translate php array to raw json
$json = json_encode($array);
// update file
file_put_contents('data.json', $json);
<?php
$c = file_get_contents('data.json');
// <- add error handling here
$data = json_decode($c, true);
// <- add error handling here, see http://docs.php.net/function.libxml-get-errors
see http://docs.php.net/file_get_contents and http://docs.php.net/json_decode