Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through array and output as pairs (divider for each second element)

I have an array with anonymous elements. Elements are added to the array via php, like so:

$playlist = array();

while (databaseloop) {
  $playlist[] = $a_title;
  $playlist[] = $a_length;
}

echo json_encode(array('playlist'=>$playlist));

So the array becomes:

["Hello.mp3", "00:00:14", "Byebye.mp3", "00:00:30", "Whatsup.mp3", "00:00:07", "Goodnight.mp3", "00:00:19"] and so on

Then I retrieve this array in jquery with ajax post. All that works fine.

Now, I'm looking for a way to treat/output all array elements as pairs in javascript/jquery. "do something" for each second element. Like this:

foreach (two_elements_in_array) {
  // output track name
  // output track time
  // output some divider
}

How can this be done?

like image 966
mowgli Avatar asked May 28 '12 14:05

mowgli


People also ask

How do you find the second element of an array?

To get the second to last element in an array, use bracket notation to access the array at index array. length - 2 , e.g. arr[arr. length - 2] . The last element in an array has an index of array.

What property of the array can be used when looping?

A for loop can be used to access every element of an array. The array begins at zero, and the array property length is used to set the loop end.

What is the syntax to loop through arrays?

Using forEach loop forEach loop is a modern way to loop through the array. Also, it gives more flexibility and control over the array and elements.

Which of the following can loop through an array without referring to the elements by index?

While a traditional for loop often loops through an array, it uses an index to do so, making Option B incorrect. The for-each loop goes through each element, storing it in a variable. Option C is correct.


1 Answers

Well, maybe this is the most basic solution:

for (var i = 0; i < arr.length; i += 2) {
    var title = arr[i];
    var len = arr[i+1];
}

However, I would recommend you to arrange $playlist as follows:

while (databaseloop) {
    $playlist[] = array(
        "title" => $a_title,
        "length" => $a_length
    );
}

Then it will be easy to iterate the elements simply with:

for (var i = 0; i < arr.length; i++) {
    var title = arr[i]['title'];
    var len = arr[i]['length'];
}
like image 153
VisioN Avatar answered Oct 03 '22 08:10

VisioN