• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP SplStack类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中SplStack的典型用法代码示例。如果您正苦于以下问题:PHP SplStack类的具体用法?PHP SplStack怎么用?PHP SplStack使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了SplStack类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: parse

 public function parse($code)
 {
     $ary = new BrainDog_OpArray();
     $pst = new SplStack();
     foreach (str_split($code) as $op) {
         $idx = count($ary);
         switch ($op) {
             case self::OP_GT:
             case self::OP_LT:
             case self::OP_ADD:
             case self::OP_SUB:
             case self::OP_DOT:
             case self::OP_COM:
                 $ary[$idx] = new BrainDog_OpCode($op);
                 break;
             case self::OP_LBR:
                 $pst->push($idx);
                 $ary[$idx] = new BrainDog_OpCode($op);
                 break;
             case self::OP_RBR:
                 $pos = $pst->pop();
                 $ary[$pos]->jmp = $idx;
                 $ary[$idx] = new BrainDog_OpCode($op, $pos - 1);
                 break;
         }
     }
     return $ary;
 }
开发者ID:rsky,项目名称:phpkansai-party-lt,代码行数:28,代码来源:BrainDog.php


示例2: LoadV2

 /**
  * 加载指定目录下的配置并生成[绝对路径=>配置]
  * (备用)
  *
  * @param        $filePath
  * @param string $ext
  */
 private function LoadV2($filePath, $ext = '.php')
 {
     $resConfig = [];
     $split = '.';
     if (file_exists($filePath)) {
         $key = basename($filePath, $ext);
         $configs = (include $filePath);
         $keyStack = new \SplStack();
         $keyStack->push([$key, $configs]);
         $whileCount = 0;
         //防止意外进入死循环,限制最多循环1024层
         while (!$keyStack->isEmpty() && $whileCount < 1024) {
             $whileCount++;
             $pair = $keyStack->pop();
             foreach ($pair[1] as $pairKey => $pairVal) {
                 if (is_array($pairVal)) {
                     $keyStack->push([$pair[0] . $split . $pairKey, $pairVal]);
                 } else {
                     $resConfig[$pair[0] . $split . $pairKey] = $pairVal;
                 }
             }
         }
     }
     return $resConfig;
 }
开发者ID:szyhf,项目名称:DIServer,代码行数:32,代码来源:Base.php


示例3: evaluateRPN

 /**
  * Evaluate array sequence of tokens in Reverse Polish notation (RPN)
  * representing mathematical expression.
  * 
  * @param array $expressionTokens
  * @return float
  * @throws \InvalidArgumentException
  */
 private function evaluateRPN(array $expressionTokens)
 {
     $stack = new \SplStack();
     foreach ($expressionTokens as $token) {
         $tokenValue = $token->getValue();
         if (is_numeric($tokenValue)) {
             $stack->push((double) $tokenValue);
             continue;
         }
         switch ($tokenValue) {
             case '+':
                 $stack->push($stack->pop() + $stack->pop());
                 break;
             case '-':
                 $n = $stack->pop();
                 $stack->push($stack->pop() - $n);
                 break;
             case '*':
                 $stack->push($stack->pop() * $stack->pop());
                 break;
             case '/':
                 $n = $stack->pop();
                 $stack->push($stack->pop() / $n);
                 break;
             case '%':
                 $n = $stack->pop();
                 $stack->push($stack->pop() % $n);
                 break;
             default:
                 throw new \InvalidArgumentException(sprintf('Invalid operator detected: %s', $tokenValue));
                 break;
         }
     }
     return $stack->top();
 }
开发者ID:aboyadzhiev,项目名称:php-math-parser,代码行数:43,代码来源:Parser.php


示例4: testPrintTraversable

 function testPrintTraversable()
 {
     $stack = new \SplStack();
     $stack->push('foo');
     $stack->push('bar');
     $this->assertEquals("<SplStack>['bar', 'foo']", ValuePrinter::serialize($stack));
 }
开发者ID:watoki,项目名称:reflect,代码行数:7,代码来源:PrintValuesTest.php


示例5: run

 /**
  * Run the pathfinder algorithm
  *
  * @return \SplStack
  */
 public function run()
 {
     $start = $this->start;
     $goal = $this->goal;
     $open = new Set([$start], function (NodeInterface $node) use($goal) {
         return $this->getHeuristic($goal, $node);
     });
     $closed = new Set();
     $open->add($start);
     $path = new \SplStack();
     $step = null;
     while (!$open->isEmpty()) {
         $current = $open->current();
         $path->push($current->getNode());
         $step = new Step($current->getNode(), $step);
         if ($current->getNode() == $goal) {
             break;
         }
         $closed->add($current->getNode());
         $neighbours = $current->getNode()->getNeighbours();
         foreach ($neighbours as $neighbour) {
             if ($closed->has($neighbour)) {
                 continue;
             }
             if (!$open->has($neighbour)) {
                 $open->add($neighbour, $this->getHeuristic($current->getNode(), $neighbour) + $neighbour->getCost());
             }
         }
     }
     return $path;
 }
开发者ID:choccybiccy,项目名称:pathfinder,代码行数:36,代码来源:Path.php


示例6: stackedCoroutine

 /**
  * Resolves yield calls tree
  * and gives a return value if outcome of yield is CoroutineReturnValue instance
  *
  * @param \Generator $coroutine nested coroutine tree
  * @return \Generator
  */
 private static function stackedCoroutine(\Generator $coroutine)
 {
     $stack = new \SplStack();
     while (true) {
         $value = $coroutine->current();
         // nested generator/coroutine
         if ($value instanceof \Generator) {
             $stack->push($coroutine);
             $coroutine = $value;
             continue;
         }
         // coroutine end or value is a value object instance
         if (!$coroutine->valid() || $value instanceof CoroutineReturnValue) {
             // if till this point, there are no coroutines in a stack thatn stop here
             if ($stack->isEmpty()) {
                 return;
             }
             $coroutine = $stack->pop();
             $value = $value instanceof CoroutineReturnValue ? $value->getValue() : null;
             $coroutine->send($value);
             continue;
         }
         $coroutine->send((yield $coroutine->key() => $value));
     }
 }
开发者ID:zavalit,项目名称:corouser,代码行数:32,代码来源:StackedCoroutineTrait.php


示例7: notify

 /**
  * @return \SplStack
  */
 public function notify()
 {
     $pilhaNotificacoes = new \SplStack();
     foreach ($this->observers as $value) {
         $pilhaNotificacoes->push($value->update($this));
     }
     return $pilhaNotificacoes;
 }
开发者ID:he--,项目名称:liquidaJp,代码行数:11,代码来源:Item.php


示例8: stack

 private function stack($items)
 {
     $stack = new \SplStack();
     foreach ($items as $item) {
         $stack->push($item);
     }
     return $stack;
 }
开发者ID:rtens,项目名称:mockster3,代码行数:8,代码来源:MatchArgumentsTest.php


示例9: firstrun

 protected function firstrun()
 {
     $data = new \SplStack();
     foreach ($this->source as $val) {
         $data->push($val);
     }
     parent::__construct($data);
 }
开发者ID:halfnelson,项目名称:LINQ4PHP,代码行数:8,代码来源:ReverseIterator.php


示例10: testSend

 /**
  * @depends testGetStack
  * @covers Versionable\Ration\Client\Pipeline::send
  * @covers Versionable\Ration\Client\Pipeline::getStack
  */
 public function testSend()
 {
     $request = $this->getMock('Versionable\\Ration\\Request\\Request');
     $stack = new \SplStack();
     $stack->push($request);
     $this->object->send($request);
     $this->assertEquals($stack, $this->object->getStack());
 }
开发者ID:versionable,项目名称:ration,代码行数:13,代码来源:PipelineTest.php


示例11: shortestPath

 public function shortestPath($source, $target)
 {
     // array of best estimates of shortest path to each
     // vertex
     $dist = array();
     // array of predecessors for each vertex
     $prev = array();
     $vertex = array();
     foreach ($this->graph as $v => $adj) {
         $vertex[$v] = 1;
         foreach ($adj as $w => $cost) {
             $vertex[$w] = 1;
         }
     }
     foreach ($vertex as $v => $value) {
         $dist[$v] = 1;
         $prev[$v] = null;
     }
     $dist[$source] = -1;
     while (!empty($vertex)) {
         $min = 2;
         $u = null;
         foreach ($vertex as $v => $value) {
             if ($dist[$v] < $min) {
                 $min = $dist[$v];
                 $u = $v;
             }
         }
         unset($vertex[$u]);
         if (isset($this->graph[$u])) {
             foreach ($this->graph[$u] as $n => $cost) {
                 $alt = -abs($dist[$u] * $cost);
                 if ($alt < $dist[$n]) {
                     $dist[$n] = $alt;
                     $prev[$n] = $u;
                 }
             }
         }
     }
     // we can now find the shortest path using reverse
     // iteration
     $S = new \SplStack();
     // shortest path with a stack
     $u = $target;
     $dist = 1;
     // traverse from target to source
     while (isset($prev[$u]) && $prev[$u] && $u != $source) {
         $S->push($u);
         $dist *= $this->graph[$prev[$u]][$u];
         // add distance to predecessor
         $u = $prev[$u];
     }
     if ($u != $source) {
         return 0;
     }
     return $dist;
 }
开发者ID:quanyang,项目名称:cs3219-project,代码行数:57,代码来源:Dijkstra.php


示例12: getParamsStack

 public function getParamsStack()
 {
     if (null === $this->paramsStack) {
         $this->paramsStack = new \SplStack();
         if ($this->getParentCommand() instanceof CommandInterface) {
             $this->paramsStack->push($this->getParentCommand()->getParams());
         }
     }
     return $this->paramsStack;
 }
开发者ID:deltaphp,项目名称:operator,代码行数:10,代码来源:PreCommand.php


示例13: solve

 private function solve($formula)
 {
     $findSubFormula = false;
     $stringStart = 0;
     $stringLength = 0;
     $stack = new \SplStack();
     $subFormulas = [];
     for ($i = 0; $i < strlen($formula); $i++) {
         $char = $formula[$i];
         if ($this->isBracketOpen($char)) {
             if ($findSubFormula == false && $stack->count() == 0) {
                 $stringStart = $i;
             }
             $stack->push(1);
             $findSubFormula = true;
         }
         if ($findSubFormula) {
             $stringLength++;
         }
         if ($this->isBracketClose($char)) {
             $stack->pop();
             if ($stack->count() === 0 && $findSubFormula) {
                 $subFormulas[substr($formula, $stringStart, $stringLength)] = substr($formula, $stringStart, $stringLength);
                 $findSubFormula = false;
                 $stringLength = 0;
             }
         }
     }
     if (count($subFormulas) > 0) {
         foreach ($subFormulas as &$subFormula) {
             $temp = trim(substr($subFormula, 1, strlen($subFormula) - 2));
             $subFormula = $this->solve($temp);
         }
         $formula = str_replace(array_keys($subFormulas), array_values($subFormulas), $formula);
     }
     $elems = new \SplDoublyLinkedList();
     array_map(function ($item) use($elems) {
         if ($item != ' ') {
             $elems->push($item);
         }
     }, explode(' ', $formula));
     while ($elems->count() > 1) {
         $maxPriority = 0;
         $index = 0;
         foreach ($elems as $i => $el) {
             if (isset(static::$symbols[$el]) && static::$symbols[$el] > $maxPriority) {
                 $maxPriority = static::$symbols[$el];
                 $index = $i;
             }
         }
         $this->process($index, $elems);
     }
     return $elems->pop();
 }
开发者ID:ygto,项目名称:calculator,代码行数:54,代码来源:Calculator.php


示例14: foreach

 /**
  * @param mixed $uid
  * @return \SplStack
  */
 public function &findAll($uid)
 {
     $result = new \SplStack();
     /** @var Node $node */
     foreach ($this->getIterator() as $node) {
         if ($node->getUid() == $uid) {
             $result->push($node);
         }
     }
     return $result;
 }
开发者ID:badlamer,项目名称:hhvm,代码行数:15,代码来源:bug65328.php


示例15: testForValidValues

 public function testForValidValues()
 {
     $var = new \SplStack();
     $var->push(1);
     $var->push(2);
     $var->push(3);
     $data = new VariableWrapper(get_class($var), $var);
     $result = $this->inspector->get($data);
     $this->assertInstanceOf('Ladybug\\Plugin\\Extra\\Type\\CollectionType', $result);
     $this->assertCount(3, $result);
 }
开发者ID:raulfraile,项目名称:ladybug-plugin-extra,代码行数:11,代码来源:SplStackTest.php


示例16: getPathTo

 public function getPathTo($endVertex)
 {
     if (!$this->hasPathTo($endVertex)) {
         return null;
     }
     $path = new \SplStack();
     for ($i = $endVertex; $i != $this->startVertex; $i = $this->edgeTo[$i]) {
         $path->push($i);
     }
     $path->push($this->startVertex);
     return $path;
 }
开发者ID:tiger-seo,项目名称:algorithms,代码行数:12,代码来源:DepthFirstPaths.php


示例17: find_path

/**
 * Поиск самого дешёвого пути между двумя локациями
 * Для поиска используется алгоритм Дейкстры
 *
 * @see http://www.sitepoint.com/data-structures-4/
 *
 * @param array  $data   Массив с локациями и ценой проезда между ними [][src, dst, cost]
 * @param string $source Название исходного пункта
 * @param string $target Название конечного пункта
 *
 * @return SplStack
 */
function find_path(array $data, $source, $target)
{
    $graph = build_graph($data);
    // массив лучших цен кратчайшего пути для каждой локации
    $best_cost = [];
    // массив предыдущих локаций для каждой локации
    $prev_loc = array();
    // очередь из необработанных локаций
    $queue = new SplPriorityQueue();
    foreach ($graph as $src => $dst) {
        $best_cost[$src] = INF;
        // изначальные значения цен бесконечны
        $prev_loc[$src] = null;
        // предыдущие локации неизвестны
        foreach ($dst as $name => $cost) {
            // используем цену как приоритет в очереди
            $queue->insert($name, $cost);
        }
    }
    // цена поездки в исходный пункт = 0
    $best_cost[$source] = 0;
    while (!$queue->isEmpty()) {
        // получаем минимальную цену
        $u = $queue->extract();
        if (empty($graph[$u])) {
            continue;
        }
        // обрабатываем доступные маршруты для локации
        foreach ($graph[$u] as $v => $cost) {
            // альтернативная цена для маршрута
            $alt = $best_cost[$u] + $cost;
            if ($alt < $best_cost[$v]) {
                // обновляем минимальную цену для локации
                $best_cost[$v] = $alt;
                // добавляем локацию в массив предыдущих локаций
                $prev_loc[$v] = $u;
            }
        }
    }
    // ищем дешёвый путь и складываем его в стек
    $stack = new SplStack();
    $u = $target;
    $final_cost = 0;
    // проходим в обратном порядке от пункта назначения к исходному пункту
    while (isset($prev_loc[$u]) && $prev_loc[$u]) {
        $stack->push($u);
        $final_cost += $graph[$u][$prev_loc[$u]];
        $u = $prev_loc[$u];
    }
    $stack->push($source);
    return [$stack, $final_cost];
}
开发者ID:nafigator,项目名称:travel-calculator,代码行数:64,代码来源:index.php


示例18: isPalindrome

function isPalindrome($word)
{
    $word = strtolower(str_replace(" ", "", $word));
    $stack = new SplStack();
    $cnt = strlen($word);
    for ($i = 0; $i < $cnt; ++$i) {
        $stack->push($word[$i]);
    }
    $rword = "";
    while ($stack->count() > 0) {
        $rword .= $stack->pop();
    }
    return $word == $rword;
}
开发者ID:kapsilon,项目名称:Specialist,代码行数:14,代码来源:15-Stack.php


示例19: getStackAsString

 /**
  * @param \SplStack $metadataStack
  * @return null|string
  */
 protected function getStackAsString(\SplStack $metadataStack)
 {
     if ($metadataStack->count() > 1) {
         $propertyNames = [];
         foreach ($metadataStack as $metadata) {
             if ($metadata instanceof PropertyMetadata) {
                 $propertyNames[] = $metadata->name;
             }
         }
         $propertyNames = array_reverse($propertyNames);
         return implode('.', $propertyNames);
     }
     return null;
 }
开发者ID:glavweb,项目名称:GlavwebRestBundle,代码行数:18,代码来源:ScopeExclusionStrategy.php


示例20: pushProcessor

 /**
  * @inheritdoc
  */
 public function pushProcessor(ProcessorInterface ...$processors)
 {
     $this->initProcessors();
     foreach ($processors as $processor) {
         $this->processors->push($processor);
     }
 }
开发者ID:oqq,项目名称:minc-log,代码行数:10,代码来源:ProcessorContainerTrait.php



注:本文中的SplStack类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP SplSubject类代码示例发布时间:2022-05-23
下一篇:
PHP SplQueue类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap