I am having one problem with the PHP json_encode function. It encodes numbers as strings, e.g.
array('id' => 3)
becomes
"{ ["id": "3", ...)
When js encounters these values, it interprets them as strings and numeric operations fail on them. Does anyone know some way to prevent json_encode from encoding numbers as strings? Thank you!
Note that since PHP 5.3.3, there's a flag for auto-converting numbers (the options parameter was added in PHP 5.3.0):
$arr = array( 'row_id' => '1', 'name' => 'George' );
echo json_encode( $arr, JSON_NUMERIC_CHECK ); // {"row_id":1,"name":"George"}
I, likewise was reading from a DB (PostgreSQL) and everything was a string. We loop over each row and do things with it to build up our final results array, so I used
$result_arr[] = array($db_row['name'], (int)$db_row['count']);
within the loop to force it to be an integer value. When I do json_encode($result_arr) now, it correctly formats it as a number. This allows you to control what is and is not a number coming from your database.
EDIT:
The json_encode() function also has the ability to do this on the fly using the JSON_NUMERIC_CHECK flag as a second argument to it. You need to be careful using it though as shown in this users example in the documentation (copied below): http://uk3.php.net/manual/en/function.json-encode.php#106641
<?php
// International phone number
json_encode(array('phone_number' => '+33123456789'), JSON_NUMERIC_CHECK);
?>
And then you get this JSON:
{"phone_number":33123456789}
I've done a very quick test :
$a = array(
'id' => 152,
'another' => 'test',
'ananother' => 456,
);
$json = json_encode($a);
echo $json;
This seems to be like what you describe, if I'm not mistaken ?
And I'm getting as output :
{"id":152,"another":"test","ananother":456}
So, in this case, the integers have not been converted to string.
Still, this might be dependant of the version of PHP we are using : there have been a couple of json_encode related bugs corrected, depending on the version of PHP...
This test has been made with PHP 5.2.6 ; I'm getting the same thing with PHP 5.2.9 and 5.3.0 ; I don't have another 5.2.x version to test with, though :-(
Which version of PHP are you using ? Or is your test-case more complex than the example you posted ?
Maybe one bug report on http://bugs.php.net/ could be related ? For instance, Bug #40503 : json_encode integer conversion is inconsistent with PHP ?
Maybe Bug #38680 could interest you too, btw ?
try
$arr = array('var1' => 100, 'var2' => 200);
$json = json_encode( $arr, JSON_NUMERIC_CHECK);
But it just work on PHP 5.3.3. Look at this PHP json_encode change log
http://php.net/manual/en/function.json-encode.php#refsect1-function.json-encode-changelog
I'm encountering the same problem (PHP-5.2.11/Windows). I'm using this workaround
$json = preg_replace( "/\"(\d+)\"/", '$1', $json );
which replaces all (non-negative, integer) numbers enclosed in quotes with the number itself ('"42"' becomes '42').
See also this comment in PHP manual.
The following test confirms that changing the type to string causes json_encode() to return a numeric as a JSON string (i.e., surrounded by double quotes). Use settype(arr["var"], "integer") or settype($arr["var"], "float") to fix it.
<?php
class testclass {
public $foo = 1;
public $bar = 2;
public $baz = "Hello, world";
}
$testarr = array( 'foo' => 1, 'bar' => 2, 'baz' => 'Hello, world');
$json_obj_txt = json_encode(new testclass());
$json_arr_txt = json_encode($testarr);
echo "<p>Object encoding:</p><pre>" . $json_obj_txt . "</pre>";
echo "<p>Array encoding:</p><pre>" . $json_arr_txt . "</pre>";
// Both above return ints as ints. Type the int to a string, though, and...
settype($testarr["foo"], "string");
$json_arr_cast_txt = json_encode($testarr);
echo "<p>Array encoding w/ cast:</p><pre>" . $json_arr_cast_txt . "</pre>";
?>
So Pascal MARTIN isn't getting enough credit here. Checking for numeric values on every JSON return is not feasable for an existing project with hundreds of server side functions.
I replaced php-mysql with php-mysqlnd, and the problem went away. Numbers are numbers, strings are strings, booleans are boolean.
For sake of completeness (as I can't add comments yet), let me also add this detail as another answer:
(Edit: To be read after realizing that the source data (i.e. in the OP's case, database result set) could be the problem (by returning numeric columns as strings), and json_encode() in fact was not the source of the problem)
Manual pages of both "mysql_fetch_array":
Returns an array of strings that corresponds to the fetched row,
... and "mysql_ fetch_ row":
Returns an numerical array of strings that corresponds to the fetched
row
clearly states that; the entries in the returned array will be strings.
(I was using the DB class in phpBB2 (yes I know, it's obsolete!), and "sql_fetchrow()" method of that class uses "mysql_fetch_array()")
Not realizing that, I also ended up finding this question, and understanding the problem! :)
As Pascal Martin stated above in his follow-up comments, I believe a solution that takes care of the "incorrect type" problem at the source (i.e. by using the "mysql_field_type()" function and doing the casting right after fetch, (or other fetch methods like "object"?)) would be the better in general.
I also had the same problem processing data from the database. Basically the problem is that the type in the array to convert in json, is recognized by PHP as a string and not as integer.
In my case I made a query that returns data from a DB column counting row. The PDO driver does not recognize the column as int, but as strings. I solved by performing a cast as int in the affected column.
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$r["id"] = intval($r["id"]);
$rows[] = $r;
}
print json_encode($rows);
it is php version the problem, had the same issue upgraded my php version to 5.6 solved the problem
Casting the values to an int or float seems to fix it. For example:
$coordinates => array(
(float) $ap->latitude,
(float) $ap->longitude
);
You can use (int) if any issue occurs!! It will work fine.
I have this problem in a curl sending json that required some fields to be integer and other fields string, but some of the values of the string fields were in fact numbers so JSON_NUMERIC_CHECK didn't worked because it converted everything that looked as a number to number.
The solution I've found was to add characters representing future double quotes, in my case I've used # as I knew it was impossible to have this character in my data, to the fields representing string values
$analysis = array(
'SampleAnalysisId' => $record[3],
'DisplayValue' => '#'.$record[4].'#',
'MeasurementUnit' => '#'.$record[5].'#',
'SampleAnalysisConclusionId' => $record[6],
'Uncertaint' => '#'.$record[7].'#',
'K' => '',
'QuantificationLimit' => '#'.$record[8].'#',
'DetectionLimit' => '#'.$record[9].'#',
'Veff' => ''
);
Then after encoding I replaced the double quotes for empty and then replaced the '#' for double quotes.
$str = json_encode($analysis,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
$str = str_replace('#','"',str_replace('",',',',str_replace(':"',':',$str)));
Resulting in a formatted json according to my need
[{"SampleAnalysisId":10479,"DisplayValue":"6,3","MeasurementUnit":"mg/L","SampleAnalysisConclusionId":1,"Uncertaint":"0,194463","K":,"QuantificationLimit":"1","DetectionLimit":"0,30","Veff":"}]
Just run into the same problem and was the database returning the values as strings.
I use this as a workaround:
$a = array(
'id' => $row['id'] * 1,
'another' => ...,
'ananother' => ...,
);
$json = json_encode($a);
That is multiplying the value by 1 to cast it into a number
Hope that helps someone
json_encode serializes some data structure in JSON format to be send across the network. Therefore all content will be of the type string. Just like when you receive some parameter from $_POST or $_GET.
If you have to make numeric operations on the values sent, just convert them to int first (with the intval() function in PHP or parseInt() in Javascript) and then execute the operations.
Well, PHP json_encode() returns a string.
You can use parseFloat() or parseInt() in the js code though:
parseFloat('122.5'); // returns 122.5
parseInt('22'); // returns 22
parseInt('22.5'); // returns 22
Like oli_arborum said, I think you can use a preg_replace for doing the job. Just change the command like this :
$json = preg_replace('#:"(\d+)"#', ':$1', $json);
I am able to parse data from youtube gdata. For example:
$json_output = json_decode($json,TRUE);
foreach ( $json_output['data']['items'] as $data ){
echo $data['content'][1]
. '</br>'
. $data['title'];
These give me rtsp url and title. Now suppose I want some other elements to add to the output (I don't possess knowledge of php, so I don't know the terms actually). What I want, that the output should have an another variable, let's take 'Boys'. This variable will have index key values same as youtube gdata and will be as follows:
Boys="You", "Me", "He", "Doggy",.....nth value.
My above code gives two values each time-url and title. Now I want the 3rd value which will be added to that from 'Boys'.
I tried Array_push as follows but it adds as an extra element and not as a variable like 'title' or 'content'.
$Boys= array('demi', 'ffe', 'erere');
array_push($json_output['data']['items'], $Boys );
How to properly insert Boys as variable? is there other methods like merge etc. to do it?
Again, since I am not a coder, please pardon my words!
Let's say you have 2 arrays with same keys, then you can do array_merge_recursive() to merge them together.
Here is a working example,
$a = [ 'boys' => ['play', 'sing']];
$b = ['boys' => 'fight'];
$merged = array_merge_recursive($a, $b);
print_r($merged);
Question is related with example from here http://lv1.php.net/array_merge
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
Usually I use such code $result2 = array_merge( array($beginning), $end );
$end is already an array. Why need (array)$end....
Tested and see the same result.
So question. Is array_merge( array($beginning), $end ) correct code?
Seems now understood why it is reasonable to use (array)
For example $var2 = array('test2');
print_r( array($var2) );
would be multidimensional array
but
print_r( (array)$var2 );
would be the same array as initial.
There is a slight difference between array($foo) and (array)$foo, but it won't affect the output.
While array($foo) will try to build an array out of $foo, obviously returning an array, (array)$foo will try to look at$foo like it is an array, hence returning an array. Both have the exact same result if your variable is a good candidate for an array, but (array)$foo may have a stronger semantic aspect since it exposes your intention of using the variable as an array, rather than building an array out of it.
array_merge only accepts parameters of type array (Since PHP 5.0)
Convert all parameters use typecasting, therefore
Add (array) before the variable, it's means convert the data type into array, case it is not array.
Note:
If you can ensure all of the variables which used in array_merge ARE array. You can direct access it, instead of adding the (array).
Yes, it's correct code. If you are sure that the parameter is already an array you don't need the type casting.
Is it possible in php to change the name used to create an associative array? I am using mongo in php but it's getting confusing using array() in both cases of indexed arrays and associative arrays. I know you can do it in javascript by stealing the Array.prototype methods but can it be done in php my extending the native object? it would be much easier if it was array() and assoc() they would both create the same thing though.
EDIT -------
following Tristan's lead, I made this simple function to easily
write in json in php. It will even take on variable from within
your php as the whole thing is enclosed in quotes.
$one = 'newOne';
$json = "{
'$one': 1,
'two': 2
}";
// doesn't work as json_decode expects quotes.
print_r(json_decode($json));
// this does work as it replaces all the single quotes before
// using json decode.
print_r(jsonToArray($json));
function jsonToArray($str){
return json_decode(preg_replace('/\'/', '"', $str), true);
}
In PHP there is no "name used to create an associative array" or "name used to create an indexed array". PHP Arrays are ordered maps like in many other scripting languages.
This means that you can use an array whichever way you please.
If you wanted an indexed array..
$indexedArray = array();
$indexedArray[] = 4; // Append a value to the array.
echo $indexedArray[0]; // Access the value at the 0th index.
Or even..
$indexedArray = [0, 10, 12, 8];
echo $indexedArray[3]; // Outputs 8.
If you want to use non integer keys with your array, you simply specify them.
$assocArray = ['foo' => 'bar'];
echo $assocArray['foo']; // Outputs bar.
I'm not 100% but this ($settings) would be called an array in php:
$setting;
$setting['host'] = "localhost";
$setting['name'] = "hello";
but what's the name for this that's different to the above:
$settings = array("localhost", "hello");
Also from the first example how can i remove the element called name?
(please also correct my terminology if I have made a mistake)
I'm not 100% but this ($settings)
would be called an array in php:
You should be 100% sure, they are :)
but what's the name for this that's
different to the above:
This:
$setting['host'] = "localhost";
$setting['name'] = "hello";
And this are different ways of declaring a php array.
$settings = array("localhost", "hello");
In fact this is how later should be to match the first one with keys:
$settings = array("host" => "localhost", "name" => "hello");
Also from the first example how can i
remove the element called name?
You can remove with unset:
unset($setting['name']);
Note that when declaring PHP array, do:
$setting = array();
Rather than:
$setting;
Note also that you can append info to arrays at the end by suffixing them with [], for example to add third element to the array, you could simply do:
$setting[] = 'Third Item';
More Information:
http://php.net/manual/en/language.types.array.php
As sAc said, they are both array. The correct way to declare an array is $settings = array(); (as opposed to just $settings; in your first line.)
The main difference between the first and second way is that the first allows you to use $settings['host'] and $settings['name'], whereas the latter can only be used with numeric indices ($settings[0] and $settings[1]). If you want to use the first way, you can also declare your array like this: $settings = array('host'=>'localhost', 'name'=>'hello');
More reading on PHP arrays
Well this is indeed an array. You have different types of array's in php. The first example you mention is called an Associative Array. Simply an array with a string as a key.
An associative array can be declared in two ways:
1) (the way you declared it):
$sample = array();
$sample["name"] = "test";
2)
$sample = array("name" => "localhost");
Furthermore the first example can also be used to add existing items to an array. For example:
$sample["name"][] = "some_name";
$sample["name"][] = "some_other_name";
When you execute the above code with print_r($sample) you get something like:
Array ( [name] => Array ( [0] => some_name [1] => some_other_name ) )
Which is very usefull when adding multiple strings to an existing array.
Removing a value from an array is very simple,
Like mentioned above, use the unset function.
unset($sample["name"])
to unset the whole name value and values connected to it
Or when you only want to unset a specific item within $sample["name"] :
unset($sample["name"][0]);
or, ofcourse any item you'd like.
So basicly.. the difference between your first example and the latter is that the first is an associative array, and the second is not.
For further reference on arrays, visit the PHP manual on arrays