I hav an array like this:
Array
(
[fruit] => Banana
[country] => Canada
)
How can I update my json file with a loop with these new datas ?
My json is a file and it looks lile this:
{"fruit" : "Cherry", "country" : "Mexico", "weight" : "28"}
Note: I want to update the value fruit and country, not all the json.
Thanks.
As i said you can decode your json as an associative array (note the use of json_decode() with second parameter set on true), loop throw it and update it while iterating. Finally encode to json again as follow
$array = array('fruit' => 'Banana', 'country' => 'Canada');
$json = '{"fruit" : "Cherry", "country" : "Mexico", "weight" : "28"}';
$mjson = json_decode($json,true);
foreach($array as $key => $val) {
if(isset($mjson[$key])) {
$mjson[$key] = $val;
}
}
$jjson = json_encode($mjson);
print_r($jjson);
//Output: {"fruit":"Banana","country":"Canada","weight":"28"}
Live demo
$input = /** some json string **/
$json = json_decode($input, true); // to assoc array
// update values
$json["fruit"] = "Cherry";
$json["country"] = "Mexico";
$json["weight"] = "28";
$ouput = json_encode($json); // back to json
// save to file etc.
Does this help?
You can't directly edit the file like it is an object.
First you need to read the file, than decode json:
e.g:
$string='{"name":"John Adams"}';
$json_a=json_decode($string,true);
Remember if you use second parameter "true" in json_a you will get associative array. Something like this:
$json_a=array("name"=>"John Adams");
But if you want to have an object don't set second parameter:
$string='{"name":"John Adams"}';
$json_o=json_decode($string);
Here json_decode($string) returns an object. Now you can do this:
echo $json_o->name;
When you modify the json object, write it back to the file.
Related
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 trying to parse some data from an API which has the result in json format.
I am successfully able to do it for one parameter as shown in the code below which outputs some data as I expect.
$json = get_content('site.tld/api.php?country=0');
$decode = json_decode($json);
echo "RUSSIA: ".$decode->kt;
I want to change the value of the country QueryString in get_content with an array (0,1,2,5,10,20 etc) which should correspondingly change the values in my echo output. Basically another set of array.
Example: 0 should correspond to RUSSIA (which is the default case). 1 to USA, 2 to Brazil, 5 to Kazakhstan and so on.
I can only think of repeating the above code for every value of country like below:
$json = get_content('site.tld/api.php?country=0');
$decode = json_decode($json);
echo "RUSSIA: ".$decode->kt;
$json = get_content('site.tld/api.php?country=1');
$decode = json_decode($json);
echo "USA: ".$decode->kt;
$json = get_content('site.tld/api.php?country=2');
$decode = json_decode($json);
echo "Brazil: ".$decode->kt;
But there are approximately 50+ parameters and I think it's a very bad code but it does work. How can I do it efficiently?
Thank you.
Use a foreach() loop and get the key/value pairs of your array and use them to dynamically display the data.
$countries = array(0 => 'Russia', 1 => 'USA', 2 => 'Brazil', 5 => 'Kazakhstan', /*and so on....*/);
// key is set in array and it equals value ex. 0 => "Russia"
or maybe
$countries = array('Russia', 'USA', 'Brazil', 'Kazakhstan', /*and so on....*/);
// key is not defined, yet exists and iterates starting at 0 then increments by 1 until the last key/value is reached inside the array
forloop($array as $key => $value){ //iterate through each key/value pair and collect data }
$stmt = null; //create an empty variable to hold your content
// loop through the array and get the key/value --> $code/$country pairs
foreach($countries as $code => $country){
$json = get_content('site.tld/api.php?country='.$code); // Code is the key
$decode = json_decode($json);
$stmt .= $country.": ".$decode->kt."<br>"; // $country is the value
}
<?=$stmt?> <--or--> <?php echo $stmt; ?> // echo out result
Let's say you have a numerically indexed array that looks like this (obtained via RedBeanPHP's find operation):
[
[33=>["name"=>"John", "age"=25]],
[55=>["name"="Jane", "age"=23]]
]
where 33 and 55 are id's of each of the 2 "beans" (basically associative-arrays).
And you want to convert the array to JSON so you can send it to a JavaScript client and use the data there as a JavaScript Object.
But you can't simply JSON_encode this because you'll end up with numerical keys in a JavaScript Object, and JavaScript doesn't like that.
What strategy can you use to convert this array to a JavaScript Object via JSON so that all the data (including id of each bean) is available at the JavaScript end? (To the RedBeanPHP folks out there: I'm hoping there's a native RedBeanPHP way to do this that I haven't found yet.)
One option is using array_map to loop thru the array. Use array_values to get all the values from the array and indexes the array numerically.
$arr = [
[33=>["name"=>"John", "age"=>25]],
[55=>["name"=>"Jane", "age"=>23]]
];
$result = array_map(function($o){
return array_values($o)[0];
}, $arr);
echo json_encode( $result );
This will result as:
[{"name":"John","age":25},{"name":"Jane","age":23}]
Simple. You should try this. First iterate through the outer array and inside that get the key i.e id of the data. Add id to other values and push that array into resultant one.
$result = array();
$arr = [[33=>["name"=>"John", "age"=>25]],[55=>["name"=>"Jane", "age"=>23]]];
foreach ($arr as $ar) {
foreach ($ar as $key => $value) {
$value['id'] = $key;
array_push($result, $value);
}
}
echo json_encode($result);
Output :-
[{"name":"John","age":25,"id":33},{"name":"Jane","age":23,"id":55}]
For your associative array:
$array = array(33 => array("name" => "John", "age" => 25), 55 => array("name" => "Jane", "age" => 23));
PHP json_encode function:
$good_json = json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
Produces JSON for JavaScript object (string "name" : value pair):
{"33":{"name":"John","age":25},"55":{"name":"Jane","age":23}}
JSON is like
{
"#http_status_code": 200,
"#records_count": 200,
"warnings": [],
"query": { ... ...
In PHP
$data = json_decode($json_entry);
print $data->#http_status_code; //returns error
print $data->http_status_code; //returns nothing
How can I retrieve status code?
1) As Object way
$data = json_decode($json_entry);
print $data->{'#http_status_code'};
2) OR use as array way by passing second argument as true in json_decode
$data = json_decode($json_entry, true);
print $data['#http_status_code'];
Try json_decode to get the json in form of array ..
$json_array = json_decode($data, true);
$required_data = $data['required_key']
with reference to your particular problem .. you will get array as
Array
(
[#http_status_code] => 200
[#records_count] => 200
[warnings] => Array
(
)
....
)
so you can access you data as $data['#http_status_code']
To access an object property that has funky characters in the name, quote the name and stick it in braces.
print $data->{'#http_status_code'};
Or, say $data = json_decode($json_entry, true); to get the data back as an array.
PHP cwill give syntax error when you do this:
$data->#http_status_code;
it looks for $http_status_code variable which is not present
so in order to make this work you have to do this:
echo $data->{'#http_status_code'};
Try this:
$data = json_decode($json_entry, true);
print $data["#http_status_code"];
I have a JSON result in PHP that looks like the following:
[{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ay6IAA"},"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ZfJIAU"},"Id":"a03U00000015ZfJIAU","Name":"ManagerID-00001"},
{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015axwIAA"},"Id":"a03U00000015axwIAA","Name":"ManagerID-00002"}]
I want to eliminate the Attributes (which contains Type and URL) so that the JSON result is flattened. So I'd like it to look more like:
[{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"}]
What is the best way in PHP to eliminate every instance of attributes?
//assign the orignal string to variable $json
$json = '[{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ay6IAA"},"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ZfJIAU"},"Id":"a03U00000015ZfJIAU","Name":"ManagerID-00001"},{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015axwIAA"},"Id":"a03U00000015axwIAA","Name":"ManagerID-00002"}]';
//decode the string with json_decode();
$decoded = json_decode($json);
//loop over the decoded array and populate array with Id and Name only
foreach($decoded as $d) $newarr[] = array('Id' => $d->Id, 'Name' => $d->Name);
//json encode the resulting array.
$finalJSON = json_encode($newarr);
Using json_decode(), array_map() and json_encode() should be easy enough:
function strip_arguments( $item){
$new_result = array(
'Id' => $item['Id'],
'Name' => $item['Name'],
)
return $new_result;
}
$array = json_decode( $input);
$array = array_map( 'strip_arguments', $array);
$input = json_encode( $array);
You of course may use unset() inside strip_arguments (instead of creating new array) but this will make sure any "new attribute" won't make it trough.
You can use return array(...) instead of declaring variable and chain operations to: json_encode(array_map( 'strip_arguments', json_decode( $input))); too :)
Using PHP's JSON's tools you can convert the JSON string into an array, from here use a simple foreach statement and REGEX to delete array entries.
Once this is done simply convert back into a JSON string using PHP functions and do with it as you please :-)
The functions I am thinking off are - json_decode, json_encode.
Thanks
Andrew