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

后端 未结 9 531
旧时难觅i
旧时难觅i 2021-01-18 03:41

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

$playlist = array();

while (databaseloop) {
  $playlist[] = $a_ti         


        
相关标签:
9条回答
  • 2021-01-18 04:03

    A simple for loop with an increment of two. You might want to make sure that your array length is long enough for i+1, in case the length isn't divisible by 2!

    for (i = 0; i+1 < array.length; i+=2) {
      name = array[i];
      length = array[i+1];
    }
    
    0 讨论(0)
  • 2021-01-18 04:05

    Not with foreach.

    for (var i = 0; i < array.length; i += 2) {
        var name = array[i];
        var time = array[i + 1];
        // do whatever
    }
    
    0 讨论(0)
  • 2021-01-18 04:09

    as @VisioN said it would be easier if you use associative array or else you can have a separated array of labels while iterating on the client side

    var d=["Hello.mp3", "00:00:14", "Byebye.mp3", "00:00:30", "Whatsup.mp3", "00:00:07", "Goodnight.mp3", "00:00:19"] ;
    var e=["name","time"];
    var c=0;
    $.each(d,function(i,j){
        if(c>=2)c=0;
        console.log(e[c]+j);
        c++;
    });
    

    http://jsfiddle.net/FmLYk/1/

    0 讨论(0)
  • 2021-01-18 04:12

    I would suggest that you optimize your code a little bit more so that it would make a bit more sense and be less error prone, if that's possible that is. This is also a great way to be more object-oriented!

    Like this (I'm using jQuery here) :

    var array = [ {name: "Hello.mp3", time: "00:00:14"}, {name: "Byebye.mp3", time:"00:00:30"}, {name: "Whatsup.mp3", time: "00:00:07"}, {name: "Goodnight.mp3", time: "00:00:19"}];
    

    Then you would be able to loop over it and produce a bit more clean looking code

    array.forEach(function(data){
        //edit the output here
        console.log(data.name + " " + data.time );  
    });
    
    0 讨论(0)
  • 2021-01-18 04:15

    You could split the array into an array of two-element arrays.

    var arr = ["Hello.mp3", "00:00:14", "Byebye.mp3", "00:00:30", "Whatsup.mp3", "00:00:07", "Goodnight.mp3", "00:00:19"];
    arr.map(function(elem,i,arr){return [elem, (i+1<arr.length) ? arr[i+1] : null];})
        .filter(function(elem,i){return !(i%2);});
    
    0 讨论(0)
  • 2021-01-18 04:16

    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'];
    }
    
    0 讨论(0)
提交回复
热议问题