如何在PHP中为JSON推送数组中的值?

时间:2013-07-24 01:18:01

标签: php json

在php中,我正在将一个数组转换为JSON字符串。

如果我对它们进行硬编码,这是有效的:

                $data = array(
                    'firstname' => mysql_result($recordset, 0, 'first name'),
                    'lastname' => mysql_result($recordset, 0, 'last name'),
                    'email' => mysql_result($recordset, 0, 'email address'),
                    'password' => mysql_result($recordset, 0, 'password'),
                    'phone' => mysql_result($recordset, 0, 'mobile number'),
                    'website' => mysql_result($recordset, 0, 'website link'),
                    'type' => mysql_result($recordset, 0, 'type_id'),
                    'active' => mysql_result($recordset, 0, 'active'),
                    'datejoined' => mysql_result($recordset, 0, 'date joined'),
                    'dateleft' => mysql_result($recordset, 0, 'date left'),
                    'datelastactive' => mysql_result($recordset, 0, 'date last active'),
                    'status' => mysql_result($recordset, 0, 'status'),
                    'biotext' => mysql_result($recordset, 0, 'bio text'),
                    'picURL' => $picURL
                );

但如果我尝试循环

            $data = array();
            for ($i = 0; $i < $num_records; $i++) {
                array_push($data, "location{$i}" => mysql_result($recordset, $i, 'location'));
            }

我收到错误

Parse error: syntax error, unexpected T_DOUBLE_ARROW

有谁知道如何解决这个问题?

由于

2 个答案:

答案 0 :(得分:5)

    $data = array();
    for ($i = 0; $i < $num_records; $i++) {
       $data["location{$i}"] = mysql_result($recordset, $i, 'location');
    }

使其关联,然后

$myJSON = json_encode($data);

获取JSON

答案 1 :(得分:2)

您需要将数组作为array_push的第二个参数。根本不要使用array_push。尝试这样的事情

$data["location{$i}"] = mysql_result($recordset, $i, 'location')));