Numbers in quotes using json_encode() [duplicate] - php

This question already has answers here:
How can I force PHP's json_encode integer values to be encoded as String?
(3 answers)
Closed 1 year ago.
Various 3rd party companies are forcing us to use non-conventional code and produce non-standard output.
We are using standard json_encode() to output a JSON variable in JS/HTML which looks like:
"custom":{"1":2,"2":7,"3":5}
Now they tell us this isn't working for them, they need it this way:
"custom":{"1":"2","2":"7","3":"5"}
Can I force PHP to wrap quotes arround numbers? Maybe using cast (string) when we build the object before encoding?
Mainly, we need an opposite of the following option bitflag:
JSON_NUMERIC_CHECK (integer)
Encodes numeric strings as numbers. Available since PHP 5.3.3.
But I doubt this exists.

Guess you need to fix this yourself. I can't think of a built-in function, but you can write your own:
function stringify_numbers($obj) {
foreach($obj as &$item)
if(is_object($item) || is_array($item))
$item = stringify_numbers($item); // recurse!
if(is_numeric($item)
$item = (string)$item;
return $obj;
}
Now you can use json_encode(stringify_numbers($yourObject))

If you're building your json data from a one-dimensional array, you can use
echo json_encode(array_map('strval', $data));
This technique will unconditionally convert all values to strings (including objects, nulls, booleans, etc.).
If your data might be multidimensional, then you'll need to call it recursively.

Related

Join strings and separate with a comma using PHP [duplicate]

This question already has answers here:
Implode all the properties of a given name in an array of object - PHP [duplicate]
(6 answers)
Closed 2 years ago.
Using PHP, I would like to select certain values from an array of objects, join them to form one continuous string separated by commas, and save this to a variable named $isbn.
I have an array of objects named $items. A var_dump($items) produces this. I need to select the item_isbn value.
My desired result is;
echo $isbn
// would produce
// '0-7515-3831-0,978-0-141-38206-7,978-1-30534-114-1'
Getting rid of the hyphens would be a bonus but I think I can achieve this using str_replace.
Here we go:
$isbnList = [];
foreach ($arrayObject as $item) {
if (isset($item->item_isbn)) {
$isbnList[] = $item->item_isbn;
}
}
$isbn = implode(",", $isbnList);
Check it:
echo $isbn;
For your information:
The foreach works because it's an array. It doesn't care each of the item inside it.
Each of the object ($item) in the loop is the default object of php (as the dump data you provided). Which is supposed to be called as $object->property. This object's property are not sure to always available, so checking whether it's available by php built-in function names isset() is essential.
By knowing implode() is built-in function from php to build a string with separator base on an one side array (means each of item in this one side array must be a scalar value (int, string)). We build this array to ready for the call.
The rest is just about syntax to how-to work with array or object... You can easily lookup on php manual page, eg: http://php.net/manual/en/language.types.array.php
Most popular programming languages nowadays provide us built-in function like this implode(), just different naming.

Is there a PHP function to encode/decode a multidimensional array in a string?

Is there a PHP function to encode a generic multidimensional array as a string and get it back as a multidimensional array?
I need it to store in mysql some data (a drupal computed field to be precise). The array contains just floats and strings.
serialize() and unserialize() do what you describe.
http://www.php.net/manual/en/function.serialize.php
http://www.php.net/manual/en/function.unserialize.php
You could also consider encoding the array as JSON with json_encode() and json_decode(), which gives more readable output, if that is important to you.
I second the use of "json_encode" and "json_decode". I believe the output of "json_encode" is less verbose than PHP's serialize function (since data types are inferred) and is immediately more portable (even though that is not a requirement).
Make sure you pass "TRUE" for the second parameter of "json_decode", otherwise you may get a simple object back, depending on how the original data was encoded.

How to access object property when property name contains - (hyphen) [duplicate]

This question already has answers here:
How do I access this object property with an illegal name?
(2 answers)
Closed 10 months ago.
I need an escape sequence for - or the minus sign for php. The object has a name-value pair where the name happens to be having - between 2 words.
I can't do this using \ the standard escape sequence (- isn't anyways documented).
I can store the name in a $myvariable which can be used but out of curiosity is it possible to do the following?
$myobject->myweird-name
This gives an Error because of -
This is what you need:
$myobject->{'myweird-name'};
If you need to look up an index, there are a couple of ways of doing it:
// use a variable
$prop = 'my-crazy-property';
$obj->$prop;
// use {}
$obj->{'my-crazy-property'};
// get_object_vars (better with a lot of crazy properties)
$vars = get_object_vars($obj);
$vars['my-crazy-property'];
// you can cast to an array directly
$arr = (array)$obj;
$arr['my-crazy-property'];
If you need to work within a string (which is not your best idea, you should be using manual concatenation where possible as it is faster and parsed strings is unnecessary), then you should use {} to basically escape the entire sequence:
$foo = new stdClass();
$foo->{"my-crazy-property"} = 1;
var_dump("my crazy property is {$foo->{"my-crazy-property"}}";
Since you mentioned that this is LinkedIn's API which, I believe, has the option of returning XML, it might be faster (and possibly cleaner/clearer) to use the XML method calls and not use the objects themselves. Food for thought.

Problem with json_encode()

i have an simple array:
array
0 => string 'Kum' (length=3)
1 => string 'Kumpel' (length=6)
when I encode the array using json_encode(), i get following:
["Kum","Kumpel"]
My question is, what is the reason to get ["Kum","Kumpel"] instead of { "0" : "Kum", "1" : "Kumpel" }?
"{}" brackets specify an object and "[]" are used for arrays according to JSON specification. Arrays don't have enumeration, if you look at it from memory allocation perspective. It's just data followed by more data, objects from other hand have properties with names and the data is assigned to the properties, therefore to encode such object you must also pass the correct property names. But for array you don't need to specify the indexes, because they always will be 0..n, where n is the length of the array - 1, the only thing that matters is the order of data.
$array = array("a","b","c");
json_encode($array); // ["a","b","c"]
json_encode($array, JSON_FORCE_OBJECT); // {"0":"a", "1":"b","2":"c"}
The reason why JSON_FORCE_OBJECT foces it to use "0,1,2" is because to assign data to obeject you must assign it to a property, since no property names are given by developer (only the data) the encoder uses array indexes as property names, because those are the only names which would make sense.
Note: according to PHP manual the options parameters are only available from PHP 5.3.
For older PHP versions refer to chelmertz's answer for a way to make json_encode to use indexes.
As Gumbo said, on the JS-side it won't matter. To force PHP into it, try this:
$a = new stdClass();
$a->{0} = "Kum";
$a->{1} = "Kumpel";
echo json_encode($a);
Not that usable, I'd stick with the array notation.
Just cast as an object and it will work fine...the JSON_FORCE_OBJECT parameter does exactly the same thing.
json_encode((object)$array);
Don't forget to convert it back into a php array so you can access its values in php:
$array = (object)$array;
$array = (array)$array;
json_encode($array);
Since you’re having a PHP array with just numeric keys, there is no need to use a JavaScript object. But if you need one, try Maiku Mori’s suggestion.
I personally think this is a bug that needs to be fixed in PHP. JSON_FORCE_OBJECT is absolutely not an answer. If you try to do any sort of generic programming you get tripped up constantly. For example, the following is valid PHP:
array("0" => array(0,1,2,3), "1" => array(4,5,6,7));
And should be converted to
{"0": [0,1,2,3], "1": [4,5,6,7]}
Yet PHP expects me to either accept
[[0,1,2,3],[4,5,6,7]]
or
{"0":{"0":1,"1":1,"2":2,"3":3},"1":{"0":4,"1":5,"2":6,"3":7}}
Neither of which are right at all. How can I possibly decode an object like that? What possible reason is there to ever change something that is clearly using strings as indexes? It's like PHP was trying to be clever to help out idiotic people who can't differentiate strings from ints, but in the process messed up anyone legitimately using strings as indexes, regardless of what the value COULD be turned into.

How can I convert all values of an array to floats in PHP?

I am fetching an array of floats from my database but the array I get has converted the values to strings.
How can I convert them into floats again without looping through the array?
Alternatively, how can I fetch the values from the database without converting them to strings?
EDIT:
I am using the Zend Framework and I am using PDO_mysql. The values are stored one per column and that is a requirement so I can't serialize them.
array_map('floatval', $array) only works on single dimensional arrays.
I can't floatval the single elements when I use them because I have to pass an array to my flash chart.
The momentary, non-generic solution is to extract the rows and do array_map('floatval',$array) with each row.
You could use
$floats = array_map('floatval', $nonFloats);
There is the option PDO::ATTR_STRINGIFY_FETCHES but from what I remember, MySQL always has it as true
Edit: see Bug 44341 which confirms MySQL doesn't support turning off stringify.
Edit: you can also map a custom function like this:
function toFloats($array)
{
return array_map('floatval', $array);
}
$data = array_map('toFloats', $my2DArray);
How are you getting your data? mysql, mysqli or PDO, some other way or even some other database?
you could use array_map with floatval like so:
$data = array_map('floatval', $data);
but that still executes a loop and i think it assumes you only have one column in your data.
you're probably best of casting to float when you use your value, if you have to. php is likely to do a good job of interpreting it right anyway.
LOL... are you working on the same project I am tharkun?
I just finished (last night) creating something, in a ZF based project, that uses pdo_mysql to retrieve and format data and then output it as xml for use in a flash piece. The values were going in as strings but needed to be floats.
Since I'm also the one who wrote the part that gets the data and the one who created the database I just made sure the data was converted to float before it went into the database.
I simply cast the values as float as part of some other formatting, for what it is worth.
protected function _c2f($input)
{
$input = (float)$input;
$output = round(($input * 1.8) + 32, 2);
return $output;
}
I found an easy way for this operation.
You can do this just by adding foreach loop to your code. foreach loop is used to fetch your array string data one by one. and then, you can simply convert this by function number_format. i used 2 place after convert to float value. i.e it used to print value after dot value 2 place.
$example= array("12.20", "15.05", "55.70");
foreach($example as $float)
{
$update_value = number_format($float,2);
echo $update_value."<br>";
}
Not sure what you're asking here? You can cast a string to a float, using (float) $string, but since PHP is dynamically typed, that will happen anyway, when needed. There is no reason to do an explicit cast.
What are you using floating point values for?

Categories