0

在 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

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

谢谢

4

2 回答 2

5

尝试

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

使其具有关联性,然后

$myJSON = json_encode($data);

获取 JSON

于 2013-07-24T01:24:43.717 回答
2

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

$data["location{$i}"] = mysql_result($recordset, $i, 'location')));
于 2013-07-24T01:21:30.470 回答