开发者

help with converting javascript function to php

开发者 https://www.devze.com 2022-12-27 15:25 出处:网络
My javascript isnt so great, but i foun开发者_如何学编程d a brilliant looking function here I\'m not sure what to do with this bit:

My javascript isnt so great, but i foun开发者_如何学编程d a brilliant looking function here

I'm not sure what to do with this bit:

var ranges = [], rstart, rend;

full function:

function getRanges(array) {
  var ranges = [], rstart, rend;
  for (var i = 0; i < array.length; i++) {
    rstart = array[i];
    rend = rstart;
    while (array[i + 1] - array[i] == 1) {
      rend = array[i + 1]; // increment the index if the numbers sequential
      i++;
    }
    ranges.push(rstart == rend ? rstart+'' : rstart + '-' + rend);
  }
  return ranges;
}

getRanges([2,3,4,5,10,18,19,20]);
// returns ["2-5", "10", "18-20"]
getRanges([1,2,3,5,7,9,10,11,12,14 ]);
// returns ["1-3", "5", "7", "9-12", "14"]
getRanges([1,2,3,4,5,6,7,8,9,10])
// returns ["1-10"]


It's almost exactly the same in PHP.

<?php

function getRanges($array){
    $ranges = array();
    for($i = 0; $i < count($array); $i++){
        $rstart = $array[$i];
        $rend = $rstart;
        while($array[$i + 1] - $array[$i] == 1){
            $rend = $array[$i + 1]; //incremenent the index if sequential
            $i++;
        }
        $ranges[] = ($rstart == $rend) ? $rstart.'' : $rstart . '-' . $rend;
    }
    return $ranges;
}

var_dump(getRanges(array(2,3,4,5,10,18,19,20)));
/*
array(3) {
  [0]=>
  string(3) "2-5"
  [1]=>
  string(2) "10"
  [2]=>
  string(5) "18-20"
}
*/

?>


Just for your information:

var ranges = [], rstart, rend;

just declares three variables ranges, rstart and rend. ranges is also initialized as an empty array.
It is the same as

var ranges = [];
var rstart;
var rend;

In PHP you don't necessarily have to declare the variables beforehand.

0

精彩评论

暂无评论...
验证码 换一张
取 消