Kam
Kam

Reputation: 6008

json encoding 2 dimension array

I have the following in php:

$query = mysql_query($sql);
$rows = mysql_num_rows($query); 
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{

    $courseData = array(
    'course_name'=>$fetch['course_name'],
    'training_field'=>$fetch['training_field'],
    'speciality_field'=>$fetch['speciality_field'],
    'language'=>$fetch['language'],
    'description'=>$fetch['description'],
    'type'=>$fetch['type'],
    );

    array_push($data['course_data'],$courseData);
}

echo json_encode($data);

when I receive the result of this script in jquery (using post)

I log it using :

console.log(data['course_data']);

and the output is :

[Object { course_name="Introduction to C++",  training_field="Engineering" ,  speciality_field="Software",  more...}]

But I can't seem to figure out how to access the elements.

I tried

data['course_data'].course_name

data['course_data']['course_name']

Nothing worked. Any ideas

Upvotes: 0

Views: 107

Answers (5)

Drmjo
Drmjo

Reputation: 584

use jquery's parseJSON method to get all the goodies out of the json object...

http://api.jquery.com/jQuery.parseJSON/

Upvotes: 0

meustrus
meustrus

Reputation: 7315

When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].

If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:

for (i in data['course_data']) {
  console.log(data['course_data'][i]['course_name']);
}

Upvotes: 1

MatRt
MatRt

Reputation: 3534

Assuming the PHP code is correct, you will receive a JSON data like:

{
    "course_num":34,
    "course_data":[
        {
            "course_name":"name_value",
            ....
        },
        ....etc (other object based on SQL result)
    ]
}

So, if you want to access to the total number of result:

data.course_num

If you want to access to the first element of the list of result:

data.course_data[0]

If you want to access to the name of the first element of the list of result:

data.course_data[0].course_name

or

data.course_data[0]['course_name']

Upvotes: 0

Kirill Kulakov
Kirill Kulakov

Reputation: 10245

You should specify the index in the first array for instance

data['course_data'][0]['course_name'];

you could make it better if you had defined the first array just as variable not a variable within an array

Upvotes: 1

Thorsten
Thorsten

Reputation: 3122

$data['course_data'][0]['course_name'] 

should do the trick. If not please send the output of var_dump($data)

Upvotes: 0

Related Questions