php json_encode single item numeric array - php

When I do json_encode from this array:
array('aps' => array(
'alert' => array(
'param1'=>array('string'),
'param2'=>'string' )));
I'm getting this JSON object:
{
"aps" : {
"alert" : {
"param1" : {
"0" : "string"
},
"param2" : "string"
}
}
}
Instead of
{
"aps" : {
"alert" : {
"param1" :
["string"],
"param2" : "string"
}
}
}
It seems to work right when the param1 array is not a single item.
How could I fix it? The Json is created from a third party bundle, so I should format the array in PHP so that I could get the correct JSON on json_encode (param1 as a list).

See this answer: https://stackoverflow.com/a/11722121/1466341
And more info here: http://www.php.net/manual/en/function.json-encode.php
Note: When encoding an array, if the keys are not a continuous numeric
sequence starting from 0, all keys are encoded as strings, and
specified explicitly for each key-value pair.
In your case everything should work fine, but I guess you have simplified your PHP array in this example. So, idea is simple - if your PHP array don't have all keys sequential, then json_encode will treat them as keys of object.

Related

Problem with json_encode() it removes the "0" key from JSON string number in PHP

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.

How to change value of special key in json using php?

I'm inserting value with implode and get this type json
[
{
"id":"1",
"f_name":"Mitrajit",
"l_name":"Samanta",
"class":"XII",
"section":"A,B,C",
"roll":"1",
"status":"1"
}
]
but I want this type :-
[
{
"f_name" : "Mitrajit",
"l_name" : "Samanta",
"class" : "XII",
"section": ["A","B","C"],
"roll" : "1",
"status" : "1"
}
]
how can I get "A,B,C" to ["A","B","C"]?
You need to use json_decode() to converting json to php array. Then select section value in json array and use explode() to converting it to array. At the end convert php array to json using json_encode()
$json = json_decode($jsonStr, true);
$json[0]["section"] = explode(",", $json[0]["section"]);
$jsonStr = json_encode($json);
Check result in demo

How to decode the syntax table to PHP array

How to decode the following syntax in PHP array:
{
'Property': {
'Lang', 'en'
, 'Make': function () {
// Do something
}
}
}
where the value of "Make" is of type string
Finally getting a table like:
echo $ array ['property'] [ 'lang']; // String
echo $ array ['property'] [ 'Make']; // String
PLEASE : It's not a standard JSON that I use, See well the Make Property.
Do you mean the function json_decode()? You can read more about it here:
http://www.php.net/manual/en/function.json-decode.php
You can use json_decode(); in your code.
json_decode($json_result);
"$json_result" your data in json type.
For your knowledge
http://www.php.net/manual/en/function.json-decode.php

Reading JSON file in PHP

I tried this code
$jsonlogcontents='{"buildings":"townhall","Army":{ "Paladins":{ "325648":0, "546545":4 }, "Knights":{ "325648":-2, "546545":0 } } }';
$phpArray = json_decode($jsonlogcontents, false);
echo $phpArray->buildings;
echo $phpArray->Army;
This is just a sample of my code, the JSON file is too large to include and has sensitive information. The problem I'm having is I can't get the value or print the value of
$phpArray->Army
It give's me an error. I can however print or get the value of
$phpArray->buildings
I'm thinking that when you decode a JSON file/contents in PHP, you can't get/print/store the value of a 'key' that has more set of info (more { and }) or brackets in it. You can only print/get values for keys who's value's contain only 1 value and nothing else.
If this is the case, what can I do to get the contents of the key that has more JSON codes in it. Also, how can I convert the contents of a key that has more JSON info in it into a string? the conversion is so I can display the value of that key to the page or echo it
The error is because Army is an object, and echo doesn't know how to convert it to a string for display. Use:
print_r($phpArray->Army);
or:
var_dump($phpArray->Army);
to see its contents.
P.S. $phpArray not an array but an object.
For Army however, I will need to do another json_decode() for that.
You don't. json_decode() decodes the entire structure in one call, into one large object (or array). No matter how deeply nested the data is, you call json_decode() once and you're done. That's why Army is not a JSON string any more.
When you are adding false as the second parameter to the json_encode it will updating all array to the sdClass empty objects.In this way you can the main array as the object
<?php
$json = '{
"buildings": "townhall",
"Army": {
"Paladins": {
"325648": 0,
"546545": 4
},
"Knights": {
"325648": -2,
"546545": 0
}
}
}';
$array = json_decode($json, true);
$object = (object)$array;
var_dump($object->Army);
?>
OUTPUT
array(2) {
["Paladins"]=>
array(2) {
[325648]=>
int(0)
[546545]=>
int(4)
}
["Knights"]=>
array(2) {
[325648]=>
int(-2)
[546545]=>
int(0)
}
}
Working Demo
It's because the output from your json_decode looks like this:
object(stdClass)(
'buildings' => 'townhall',
'Army' => object(stdClass)(
'Paladins' => object(stdClass)(
325648 => 0,
546545 => 4
),
'Knights' => object(stdClass)(
325648 => -2,
546545 => 0
)
)
)
Army is a standard object so it can't know how to echo it. You can however var_dump it:
var_dump($phpArray->Army);
The easiest solution is to treat it as a normal array with:
$phpArray = json_decode($jsonlogcontents, true);

Can you have a PHP $_POST variable that is set to an array?

I am using AJAX to put some data in my database. I am using JSON to submit the data to a PHP page. I am using a POST request. Can you set one of the POST variables as an array? Below I have the full AJAX request, but here is the part where I am setting two parts of the data as arrays:
"content[]" : testContentArray,
"content_attr[]" : testContentAttributes,
Below is my full AJAX (using jQuery):
$.ajax({
type: "POST",
url: "../includes/create_test_main.ajax.php",
data: {"tags" : $('#testTags').val(),
"title" : $('#testTitle').val(),
"subject" : $('#testSubject').val(),
"description" : $('#testDescription').val(),
"content[]" : testContentArray,
"content_attr[]" : testContentAttributes,
"user_id" : user_id},
success:
function(testId) {//redirect Page
window.location.href = "http://localhost/nvr_forget/public_html/test/" + testId + "/";
}
});
};
If that is the way to do it, how would I handle it on the PHP side? do I handle the $_POST variable as a normal array?
When you pass an array within a data object to $.ajax, it is parsed out into name[]=value format. This is done using $.param, so I'll illustrate using that:
jQuery.param({'foo': [1, 2, 5]})
// "foo%5B%5D=1&foo%5B%5D=2&foo%5B%5D=5"
%5B and %5D are uri-encoded square brackets. This is a common way of sending multiple values for the same key to a server. PHP parses it into an array, so in this case:
var_export($_POST['foo']);
// array ('1', '2', '5')
So in your code, $_POST['content'] and $_POST['content_attr'] should both be arrays. The square brackets that you've used are unnecessary, but won't break anything.
See the PHP manual on the subject.
Of course you can - it can be either simple array (with integers as keys) or associative array. It just depends what JSON object you submit.
For example if you submit the following JSON object:
var data = {
'a': 'test123',
'b': [
'x',
'y',
'z'
],
'c': {
'testing': 'abc',
'blah': 'qwerty'
}
}
You will have the following elements within $_POST:
$_POST['a'] - containing string test123,
$_POST['b'] - containing array (array('x','y','z')),
$_POST['c'] - also containing array, but associative (array('testing'=>'abc','blah'=>'qwerty')),
You can post an object from JS (JSON) and json_decode it on server (PHP) with json_decode.
You can probably do it, but you have to do it fully manually like so:
{
"content[0]": "a",
"content[1]": "b",
"content[2]": "c",
"content[multi][0]": "d"
}
$_POST['content'] will then look like:
Array(
0 => "a",
1 => "b",
2 => "c",
multi => Array(
0 => "d"
)
)
It would be a lot simpler to just:
{
"blob" : JSON.stringify(data_or_array_or_whatever)
}
In PHP you can then retrieve it by:
$data = json_decode($_POST['blob'], true);
This needs the json2.js library for older browsers though.
I'd go for the latter as in the former you're likely to be writing your own serializer in the end :P - which is exactly why we have JSON.

Categories