PHP foreach循环多个对象?

时间:2022-10-25 08:38:41

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

我使用PHP / codeigniter,通常循环查询结果我会做这样的事情:

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

但是,假设我有另一个对象数组$ data2,与$ data具有相同数量的对象:是否有任何有效的PHP语法允许我使用foreach语句同时访问同一循环中两个对象上的行?我知道我可以通过访问数组的indeces来定期执行for循环,但这不会那么干净。

2 个解决方案

#1


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.

这将有效地使您能够同时循环两个数组。

#2


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.

也许你可以重构代码,使得代替$ data和$ other数组,你有一个数组,其条目是一个带有 - > data和 - >其他成员的关联数组。但只有在数据模型中有意义时才应该这样做。恕我直言,在这种情况下循环索引是好的。

#1


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.

这将有效地使您能够同时循环两个数组。

#2


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.

也许你可以重构代码,使得代替$ data和$ other数组,你有一个数组,其条目是一个带有 - > data和 - >其他成员的关联数组。但只有在数据模型中有意义时才应该这样做。恕我直言,在这种情况下循环索引是好的。