Nicolaesse
Nicolaesse

Reputation: 2714

convert array element from string to number

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?

Upvotes: 1

Views: 1784

Answers (3)

artlung
artlung

Reputation: 34013

<?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]]}

Upvotes: -1

Jasper
Jasper

Reputation: 75993

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

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

Upvotes: 1

SERPRO
SERPRO

Reputation: 10067

You might want to add JSON_NUMERIC_CHECK to your json_encode function:

   json_encode($array, JSON_NUMERIC_CHECK);

Upvotes: 4

Related Questions