0

In php, I am making an array to be turned into a JSON string.

This works, if I hardcode them:

                $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
                );

But if I try a loop

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

I get the error

Parse error: syntax error, unexpected T_DOUBLE_ARROW

Does anyone know how to fix this?

Thanks

2 Answers 2

5

try

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

to make it associative, and then

$myJSON = json_encode($data);

to get JSON

Sign up to request clarification or add additional context in comments.

Comments

2

You need to put array as a second argument of array_push. Don't use array_push at all. Try something like this instead

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

2 Comments

maybe because you answer is wrong? your example returns Array([0]=>Array([location{0}]=>'somevalue'),[1]=>Array([location{1}]=>'anothervalue'), ...) not Array([location{0}]=>'somevalue',[location{1}]=>'anothervalue', ...)
What a begginer mistake -_- Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.