Mariano Hernandez
Mariano Hernandez

Reputation: 19

$.each() not working

I hope you can help me.

I have this code

var marcadores = [<?php echo $listeDesPoints; ?>];

$.each(marcadores, function( i, value ) {
  events.push({title: value[i][0], start: new Date(value[i][1], value[i][2]-1, value[i][3],value[i][4]),color: '#9b59b6'});
});
;

It's not working at the moment, and I don't know what I'm doing wrong.

Upvotes: 0

Views: 106

Answers (2)

Nathanael Smith
Nathanael Smith

Reputation: 3321

If i understand your php output correctly it looks something like

// an array of date
var marcadores = [
  ['title', 2, 10, 15, 9],
  ['other title', 3, 10, 14, 12]
  //etc
];

You're iterating over this data structure to create objects. You have an array of arrays, with your inner array more of an object

// also make sure you initialize events to be an array, otherwise you can't call push on something that is not an array
var events = [];

$.each(marcadores, function(i, value) {
    // value here is the current item in your iteration
    events.push({
        title: value[0],
        start: new Date(value[1], value[2]-1, value[3], value[4]),
        color: '#9b59b6'
    });
});

Also you'd make your life much easier if you built up a multidemnsional array in php then json_encoded it.

<?php
// clipped
$str="select asunto, day(fecha),month(fecha),year(fecha),hour(fecha) from agenda where id_persona = 77";
$consulta= mysql_query($str); 
$listeDesPoints = array();
while($row = mysql_fetch_array($consulta)) {
    $listeDesPoints[] = array(
        'title' => $row[0],
        'day' => $row[1],
        'month' => $row[2],
        'year' => $row[3],
        'hour' => $row[4]
    )
}
?>
var marcadores = <?php echo json_encode($listeDesPoints); ?>;

Then you output is

 // an array of date
 var marcadores = [{
        title: 'title',
        day: 1,
        month: 10,
        hour: 15
    }
  //etc
];

And iteration reads much better

$.each(marcadores, function(i, value) {
    // value here is the current item in your iteration
    events.push({
        title: value.title,
        start: new Date(value.day, value.month-1, value.year, value.hour),
        color: '#9b59b6'
    });
});

Upvotes: 1

cFreed
cFreed

Reputation: 4482

Your issue comes from the way you're interpreting $.each() arguments: you take value as if it was the entire marcadores array, while in fact it is only its current item.

So you only have to drop [i] from each object's building factor. Results in this:

$.each(marcadores, function( i, value ) {
  events.push({
    title: value[0],
    start: new Date(value[1], value[2] - 1, value[3], value[4]),
    color: '#9b59b6'
  });
});

Upvotes: 1

Related Questions