用循环添加array_push()元素来创建json数据 [英] adding element with array_push() with looping to create json data
问题描述
$ b
[{name:AS,data:[ 150, 250, 300]},{ 名称: JS, 数据:[ 175, 180, 210]},{ 名称: MS ,data:[100,75,200]}]
这里是脚本已创建
$ 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($ i = 0; $ i <$ cc; $ i ++)
{
$ if(count($ cb)> 1)
{
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);
}
}
,我的脚本的结果是
[{name:AS,data:[150,250,300 ]}] [{ 名称 : JS 数据:[ 175, 180, 210]}] [{ 名称: MS, 数据:[ 100 ,75,200]}]
仍然与我想要显示的内容不匹配...
编辑:WORK
$ result = array();
($ i = 0; $ i <$ cc; $ i ++)
{
$ b = mysql_query(SELECT distinct nama,jumlah FROM tcoba WHERE nama ='$ cb [$一世]');
$ rows = array();
while($ ba = mysql_fetch_array($ b))
{
$ rows ['name'] = $ ba [0];
$ rows ['data'] [] = $ ba ['jumlah'];
}
array_push($ result,$ rows);
}打印json_encode($ result);
在for循环后移动print, t将 $ result
重新初始化为循环内的空数组。
另外...
$ cc = array();
$ cc = count($ cb);
其中一条线是多余的(可能是第一条线)。
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);
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).
这篇关于用循环添加array_push()元素来创建json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!