欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP5.5新特性之yield理解與用法實(shí)例分析

 更新時間:2019年01月11日 12:00:24   作者:moliyiran  
這篇文章主要介紹了PHP5.5新特性之yield理解與用法,結(jié)合實(shí)例形式分析了php5.5 yield生成器功能、原理、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了PHP5.5新特性之yield理解與用法。分享給大家供大家參考,具體如下:

yield生成器是php5.5之后出現(xiàn)的,yield提供了一種更容易的方法來實(shí)現(xiàn)簡單的迭代對象,相比較定義類實(shí)現(xiàn) Iterator 接口的方式,性能開銷和復(fù)雜性大大降低。

yield生成器允許你 在 foreach 代碼塊中寫代碼來迭代一組數(shù)據(jù)而不需要在內(nèi)存中創(chuàng)建一個數(shù)組。

使用示例:

/**
 * 計算平方數(shù)列
 * @param $start
 * @param $stop
 * @return Generator
 */
function squares($start, $stop) {
  if ($start < $stop) {
    for ($i = $start; $i <= $stop; $i++) {
      yield $i => $i * $i;
    }
  }
  else {
    for ($i = $start; $i >= $stop; $i--) {
      yield $i => $i * $i; //迭代生成數(shù)組: 鍵=》值
    }
  }
}
foreach (squares(3, 15) as $n => $square) {
  echo $n . 'squared is' . $square . '<br>';
}

輸出:

    3 squared is 9
    4 squared is 16
    5 squared is 25
    ...

示例2:

//對某一數(shù)組進(jìn)行加權(quán)處理
$numbers = array('nike' => 200, 'jordan' => 500, 'adiads' => 800);
//通常方法,如果是百萬級別的訪問量,這種方法會占用極大內(nèi)存
function rand_weight($numbers)
{
  $total = 0;
  foreach ($numbers as $number => $weight) {
    $total += $weight;
    $distribution[$number] = $total;
  }
  $rand = mt_rand(0, $total-1);
  foreach ($distribution as $num => $weight) {
    if ($rand < $weight) return $num;
  }
}
//改用yield生成器
function mt_rand_weight($numbers) {
  $total = 0;
  foreach ($numbers as $number => $weight) {
    $total += $weight;
    yield $number => $total;
  }
}
function mt_rand_generator($numbers)
{
  $total = array_sum($numbers);
  $rand = mt_rand(0, $total -1);
  foreach (mt_rand_weight($numbers) as $num => $weight) {
    if ($rand < $weight) return $num;
  }
}

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對大家PHP程序設(shè)計有所幫助。

相關(guān)文章

最新評論