简体   繁体   中英

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. 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.

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.

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. 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.

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:

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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