adding element with array_push() with looping to create json data

吃可爱长大的小学妹 提交于 2019-12-14 03:16:00

问题


I want to create JSON data which looks like this

[{"name":"AS","data":["150","250","300"]},{"name":"JS","data":["175","180","210"]},{"name":"MS","data":["100","75","200"]}]

and here is the script that I have created

$c = mysql_query("SELECT distinct nama FROM tcoba ORDER BY nama ASC"); 
while($ca = mysql_fetch_array($c))
{
    $cb[] = $ca['nama'];
}
$cc = array();
$cc = count($cb);
if(count($cb) > 1)
{
    for($i=0;$i<$cc;$i++)
    {
        $b = mysql_query("SELECT distinct nama, jumlah FROM tcoba WHERE nama = '$cb[$i]'");
        $rows = array();
        while($ba = mysql_fetch_array($b)) 
        {
            $rows['name'] = $ba[0];
            $rows['data'][] = $ba['jumlah'];
        }
        $result = array(); 
        array_push($result,$rows);
        print json_encode($result);
    }
}

and the result from my script is

[{"name":"AS","data":["150","250","300"]}][{"name":"JS","data":["175","180","210"]}][{"name":"MS","data":["100","75","200"]}]

still not match with what I want to show...

EDIT : WORK

$result = array(); 
for($i=0;$i<$cc;$i++)
{
    $b = mysql_query("SELECT distinct nama, jumlah FROM tcoba WHERE nama = '$cb[$i]'");
    $rows = array();
    while($ba = mysql_fetch_array($b)) 
    {
        $rows['name'] = $ba[0];
        $rows['data'][] = $ba['jumlah'];
    }

    array_push($result,$rows);

}print json_encode($result);

回答1:


Move the print after the for loop, and don't reinitialize $result to an empty array inside of the loop.

Also...

$cc = array();
$cc = count($cb);

One of those lines is redundant (probably the first).




回答2:


There are two things wrong with your code:

  • you're re-inializing the array on each iteration
  • you're printing the JSON string on each iteration

What you're seeing as the output is three JSON strings combined. As there are no line breaks in your code, it'll appear as one big JSON string.

Your code should look like:

$result = array(); // initialize the array
while($ba = mysql_fetch_array($b)) 
{
    $rows['name'] = $ba[0];
    $rows['data'][] = $ba['jumlah'];
    array_push($result,$rows);
}
print json_encode($result);



回答3:


Move $result = array(); to occur before the loop, perhaps even before the if-block. You can probably handle the code from there.




回答4:


Highcharts use number data, but your data is a array of strings. So you need to parse it by parseFloat() or use json_encode() with JSON_NUMERIC_CHECK which allows to return correct JSON values.



来源:https://stackoverflow.com/questions/19275146/adding-element-with-array-push-with-looping-to-create-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!