简体   繁体   English

在PHP中执行此foreach的更好方法?

[英]Better way to do this foreach in PHP?

Is there a better way to get the same result that this produces? 是否有更好的方法来获得与之相同的结果?

foreach($data['report']->result_array() as $k){
    $array[] = $k['id'];
}

Better: in this context, meaning shorter, easier to read, or better syntax overall. 更好:在这种情况下,意味着更短,更易于阅读或总体上语法更好。

I'm a noob, so comments/suggestions/general wisdom from the programming community is welcome! 我是新手,欢迎编程社区的意见/建议/一般智慧!

I can't think of a better way to achieve this. 我想不出更好的方法来实现这一目标。

Of course, if you are able to alter the result_array() function you can introduce a new parameter to return the id field only. 当然,如果您能够更改result_array()函数,则可以引入一个新参数以仅返回id字段。 However, in my opinion this decreases the readability of the code. 但是,我认为这会降低代码的可读性。

If you only want to load the id's from $data['report'], i would suggest defining a new specialized method that returns all the id 's. 如果只想从$ data ['report']加载ID,我建议定义一个新的专门方法,该方法返回所有ID

If you simply want to extract the 'id' field from the array of data returned by the result_array function on each element of the $data['report'] and put it into a new array, then this is probably about as efficient as you can get. 如果只想从$ data ['report']的每个元素上由result_array函数返回的数据数组中提取'id'字段并将其放入一个新数组中,那么这大概和您一样高效可以得到。

Is there something about this you find troubling? 您对此感到不安吗? It looks fine to me (although I'd never name an array variable "$array" - something like $idArray seems more apt) if that's the objects/data structure you have to deal with. 如果我要处理的对象/数据结构对我来说很好(尽管我永远不会将数组变量命名为“ $ array”-像$ idArray这样的名称更合适)。 That said, I presume it's appropriately commented, etc. 就是说,我想它已经被适当地评论了,等等。

$array = array_map(function($k) { 
    return $k['id'];
}, $data['report']->result_array());

You are limited to doing just that single thing within the "loop," so I don't know if it qualifies as "better." 您仅限于在“循环”内执行单个操作,因此我不知道它是否符合“更好”的条件。 It's just different. 只是不同而已。

Some people prefer the map/reduce style of programming, but it's not very common in PHP code, as the syntax isn't that good and anonymous functions were only recently introduced. 有些人喜欢编程的map / reduce风格,但是在PHP代码中并不是很常见,因为语法不是很好,并且匿名函数只是最近才引入的。

Edit: Removed the bit about speed comparison. 编辑:删除了有关速度比较的位。

Here's one better way (at least what I would determine to be better): 这是一种更好的方法(至少我认为是更好的):

$reportIds = array();
$dataArray = $data['report']->result_array();

foreach($dataArray as $reportElement) {
    $reportIds[] = $reportElement['id'];
}

It uses more meaningful variable names (as I'm guessing), and is a little bit more verbose about what's going on. 它使用了更有意义的变量名(我猜是这样),并且对所发生的事情有些冗长。 Remember, readability trumps all other concerns with the exception of correctness. 请记住,除了正确性之外,可读性比其他所有问题都重要。

Of course, depending on the needs of what you're doing, you could also write a method to fetch only the ids (along side result_array() ) or an iterator to do this for you: 当然,根据您正在执行的操作的需要,您还可以编写一种方法来仅获取id(以及result_array() )或迭代器来为您执行此操作:

class MultiDimensionalArrayIterator extends ArrayIterator {
    protected $key = '';

    public function __construct(array $array, $key) {
        $this->key = $key;
        parent::__construct($array);
    }

    public function current() {
        $data = parent::current();
        return $data[$this->key];
    }

    public function offsetGet($index) {
        $data = parent::offsetGet($index);
        return $data[$this->key];
    }

    // Implement other overrides to consistently handle iteration
}

Usage: 用法:

$dataArray = $data['report']->result_array();
$iterator = new MultiDimensionalArrayIterator($dataArray, 'id');
$reportIds = iterator_to_array($iterator);

There are lots of possibilities. 有很多可能性。 The question comes in what do you need, and what does the rest of your project need... 问题来了,您需要什么,其余项目需要什么...

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

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