1

I've some numbers which come from a query and that I have to represent using the json_encode function. Everything work but the output looks like this

{ "label": "man", "data":[["0","1.13"], ["1","1.38"], ["2","1.87"], ["3","1.12"], ["4","1.28"]]}

so I think that the problem is that all the numbers are stored as string. Is there a function to convert all the elements in number?

1
  • 2
    "so I think that the problem is that all the numbers are stored as string." What problem? Commented Nov 10, 2011 at 22:36

3 Answers 3

4

You might want to add JSON_NUMERIC_CHECK to your json_encode function:

   json_encode($array, JSON_NUMERIC_CHECK);
Sign up to request clarification or add additional context in comments.

3 Comments

Just FYI, this was added in PHP 5.3.3.
@Rocket I know, just want to let him know the options available.
Glad I could help. You can mark the answer as correct if you want
1

You can get the integer or float value of a variable with this:

echo (integer)$variable;
echo (float)$variable;

1 Comment

That's good if I'll use the echo instead of using the json_encode...thanks everybody for the answers!
-1
<?php

$json = '{ "label": "man", "data":[["0","1.13"], ["1","1.38"], ["2","1.87"], ["3","1.12"], ["4","1.28"]]}';

$structure = json_decode($json, true);
$newData = $structure['data'];

for ($x=0;$x<count($newData);$x++):
    for ($i=0;$i<count($newData[$i]);$i++):
        $newData[$x][$i] = (float)$newData[$x][$i];
    endfor;
endfor;

$structure['data'] = $newData;
print json_encode($structure);

New Result:

{"label":"man","data":[[0,1.13],[1,1.38],[2,1.87],[3,1.12],[4,1.28]]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.