简体   繁体   中英

PHP foreach loop on multiple objects?

I am using PHP/codeigniter, and typically to loop over query results I would do something like this:

<?php foreach($data as $row):?>
//html goes here
<?php endforeach;?>

But, say I have another object array, $data2 , with the same number of objects as $data : is there any valid PHP syntax that would allow me to simultaneously access rows on both objects within the same loop using the foreach statement? I know I could do this with a regular for loop by accessing the indeces of the arrays, but this wouldn't be as clean.

You could to something like this:

<?php foreach($data as $key => $row): $row2 = $data2[$key]; ?>
//html goes here
<?php endforeach;?>

Which would effectively enable you to loop both arrays at the same time.

I think the indices are your best bet. This would be a strange language feature because in general you don't know that two arrays have the same size and what do you do when one runs out before the other?

Maybe you could refactor the code such that instead of $data and the $other array, you had a single array whose entries were an associative array with a ->data and ->other members. But that should only be done if it makes sense in the data model. IMHO, looping over the index in this case is fine.

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