简体   繁体   English

PHP 相当于 Python 的 enumerate()?

[英]PHP equivalent to Python's enumerate()?

In Python I can write:在 Python 中,我可以写:

for i, val in enumerate(lst):
    print i, val

The only way I know how to do this in PHP is:我知道如何在 PHP 中执行此操作的唯一方法是:

for($i = 0; $i < count(lst); $i++){
    echo "$i $val\n";
}

Is there a cleaner way in PHP? PHP中有更清洁的方法吗?

Don't trust PHP arrays, they are like Python dicts.不要相信 PHP 数组,它们就像 Python 字典。 If you want safe code consider this:如果您想要安全的代码,请考虑:

<?php
$lst = array('a', 'b', 'c');

// Removed a value to prove that keys are preserved
unset($lst[1]);

// So this wont work
foreach ($lst as $i => $val) {
        echo "$i $val \n";
}

echo "\n";

// Use array_values to reset the keys instead
foreach (array_values($lst) as $i => $val) {
        echo "$i $val \n";
}
?>

- -

0 a 
2 c 

0 a 
1 c 

Use foreach :使用foreach

foreach ($lst as $i => $val) {
    echo $i, $val;
}

If you want the index, key, and value, equivalent to this Python:如果你想要索引、键和值,相当于这个Python:

for ii, (key, value) in enumerate(my_dict.items()):
    print ii
    print key
    print value

You can create an enumerate function in PHP that wraps your objects.您可以在 PHP 中创建一个枚举函数来包装您的对象。 It's not meant to be efficient (it pre-iterates and collects everything) but it can be syntactically convenient.它并不意味着高效(它预先迭代并收集所有内容),但它在语法上很方便。

function enumerate($array) {
    class IterObject {
        public $index;
        public $key;
        public $value;
    }

    $collect = array();
    $ii = 0;
    foreach ($array as $key => $value) {
        $iter = new IterObject();
        $iter->index = $ii;
        $iter->key = $key;
        $iter->value = $value;
        array_push($collect, $iter);
        $ii++;
    }
    return $collect;
}

Example usage:示例用法:

foreach (enumerate($my_array) as $iter) {
    echo $iter->index;
    echo $iter->key;
    echo $iter->value;
}

I think you were looking for the range function.我认为您正在寻找范围功能。

One use case could be the pagination where (assume) you have 150 items and you want to show 10 items per page so you have 15 links.一个用例可能是分页,其中(假设)您有 150 个项目,并且您希望每页显示 10 个项目,因此您有 15 个链接。 So to create those links you can use:因此,要创建这些链接,您可以使用:

    $curpage=3;$links=15;$perpage=10; //assuming.

    <?php foreach(range(1,$links) as $i):?>
        <?php if($i==$curpage):?>
             <li class="active"><a class="active"><?=$i?></a><li>
        <?php else:?>
             <li><a href="paging_url"><?=$i?></a><li>
        <?php endif ?>
    <?php endforeach ?>

With the introduction of closures in PHP 5.3 you can also write the following:随着 PHP 5.3 中闭包的引入,您还可以编写以下代码:

array_map(function($i,$e) { /* */ }, range(0, count($lst)-1), $lst);

Of course this only works if the array is stored in a variable.当然,这仅在数组存储在变量中时才有效。

In python enumerate has start argument, to define start value of enumeration.在 python 中 enumerate 有start参数,用于定义枚举的起始值。

My solution for this in php is:我在 php 中对此的解决方案是:

function enumerate(array $array, $start = 0)
{
    $end = count($array) -1 + $start;

    return array_combine(range($start, $end), $array);
}

var_dump(enumerate(['a', 'b', 'c'], 6000));

The output is:输出是:

array(3) {
  [6000]=>
  string(1) "a"
  [6001]=>
  string(1) "b"
  [6002]=>
  string(1) "c"
}

Yes, you can use foreach loop of PHP:是的,您可以使用 PHP 的foreach循环:

 foreach($lst as $i => $val)
       echo $i.$val;

I am using the helper function:我正在使用辅助功能:

function enumerate(array &$array, callable $fn) {
    $i = 0;
    foreach ($array as $key => &$value)
        $fn($i++, $key, $value);
}

And I use it as follows:我使用它如下:

enumerate($array, function ($i, $key, &$value) use (&$something)  {
    ...
});

The downside may be that you have to pass external variables that you want to use inside the loop through the use (...) directive.缺点可能是您必须通过 use (...) 指令传递要在循环内使用的外部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM