2

I am trying to use a getJSON method in jquery to retrieve a dynamic array. I am getting an "illegal" offset error trying to encode my dynamic array. Here is the server side code (I am confident the javascript is correct because when I remove the query it runs fine):

<?php 
session_start();
require_once "database.php";
db_connect();
require_once "auth.php";
$current_user = current_user();
include_once("config.php");

$westcoast_id = $_GET['westcoast_id'];

$westcoast_array = array();


 $query = "SELECT city, state FROM users GROUP BY city";
 $result = mysql_query($query) or die(mysql_error());
 while($row = mysql_fetch_array($result)){

if($row['city'] != '' && $row['state'] != '') {
    $westcoast_array[$row] = "location:".$row['city'].", ".$row['state'].", stopover:true";


   }

}

$data = array($westcoast_id, $westcoast_array);

echo json_encode($data);


?>

The illegal offset is in reference to the line:

$westcoast_array[$row] = "location:".$row['city'].", ".$row['state'].", stopover:true";

I cannot see what the issue is. Thank you for your help!

3
  • 1
    $row is an array. How is it supposed to work as a key for another array? Commented Mar 1, 2013 at 21:39
  • Absolutely nothing to do with json. this is purely a PHP problem - you're using an incorrect array key inside your fetch loop, exactly as @DCoder is pointing out above. Commented Mar 1, 2013 at 21:40
  • It also looks like your json will have issues. Using a comma in the location value without enclosing it in quotes. Commented Mar 1, 2013 at 21:43

2 Answers 2

1
 $westcoast_array[$row] = [...]

is wrong. (you cannot use an array as a key)

Simply use:

$westcoast_array[] = [...]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this. This was my problem.
0

Try using:

if($row['city'] != '' && $row['state'] != '') {
    $westcoast_array[] = "location:".$row['city'].", ".$row['state'].", stopover:true";
}

or

if($row['city'] != '' && $row['state'] != '') {
    $westcoast_array[$row['state']][$row['city']] = "location:".$row['city'].", ".$row['state'].", stopover:true";
}

And then you can use var_dump($westcoast_array) to see the structure.

Comments

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.