将数组元素从字符串转换为数字


convert array element from string to number

我有一些来自查询的数字,必须使用json_encode函数来表示。一切正常,但输出看起来像这个

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

所以我认为问题是所有的数字都存储为字符串。有没有一个函数可以转换所有元素的数字?

您可能需要将JSON_NUMERIC_CHECK添加到JSON_encode函数中:

   json_encode($array, JSON_NUMERIC_CHECK);

您可以使用以下命令获取变量的整数值或浮点值:

echo (integer)$variable;
echo (float)$variable;
<?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);

新结果:

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