开发者

json_encode in php

开发者 https://www.devze.com 2023-02-19 13:59 出处:网络
i have this script and it works, but not as i expected. I need to assign an array of values with differents names, now all $arr[] are named \"valor\"

i have this script and it works, but not as i expected. I need to assign an array of values with differents names, now all $arr[] are named "valor"

{"valor":"20"},{"valor":"50"}

i need

{"valor1":"20"},{"valor2":"50"}

the script

    $query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());

    $arr = array();
    while($row = mysql_fetch_assoc($query)) {
        $arr[] = $row;
    }
    echo json_开发者_JS百科encode($arr);


in ajax

    <script type="text/javascript">
       jQuery(document).ready(function(){
          jQuery("button").click(function(){

             jQuery.ajax({
                url: "chart.php",
                dataType: "json", 
                success: function(json){
                   var msg = "Nome: " + json.valor1+ "\n";
                   msg += "Sobrenome: " + json.valor2 + "\n";

                   alert(msg);
                }
             });
          });
       });

       </script>

the problem is: I need to create a loop that create uniques names, as value1, value2, value3

like

$arr['valor1'] = "Evandro";

i tried a loop- for, but i get an error of memory

thanks


Try this:

$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());

$arr = array();
$i = 1;
while($row = mysql_fetch_assoc($query)) {
    $arr[] = array("valor{$i}" => $row["valor"]);
    ++$i;
}
echo json_encode($arr);

Should work. Alternatively if you want to make it so it works with current callback change the $arr[] = line to the following:

    $arr["valor{$i}"] = $row["valor"];


$index = 1;
while($row = mysql_fetch_assoc($query)) {
        $key = 'valor'.index;
        $arr[$key] = $row;
        $index++;
    }

Does that give you a memory error? It shouldn't.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号