【发布时间】:2011-12-22 05:41:18
【问题描述】:
我有一个大数组。
在这个数组中,我有(除其他外)一个产品列表:
$data['product_name_0'] = '';
$data['product_desc_0'] = '';
$data['product_name_1'] = '';
$data['product_desc_1'] = '';
这个数组是由第三方提供的(所以我无法控制)。
不知道数组中会有多少产品。
循环所有产品的干净方法是什么?
我不想使用foreach 循环,因为它还会遍历(大)数组中的所有其他项。
我不能使用for 循环,因为我不知道(还)数组包含多少产品。
我可以做一个while循环:
$i = 0;
while(true) { // doing this feels wrong, although it WILL end at some time (if there are no other products)
if (!array_key_exists('product_name_'.$i, $data)) {
break;
}
// do stuff with the current product
$i++;
}
有没有更清洁的方法来完成上述操作?
while(true) 在我看来很愚蠢,或者这种方法没有任何问题。
或者也许还有其他方法?
【问题讨论】: