【发布时间】:2012-02-18 23:54:33
【问题描述】:
我使用foreach循环下面的数组,然后将订单号存入数据库,
$items_variable = array(
'page_id',
'page_content_1',
'page_content_2',
'page_content_3',
'page_content_4',
...
);
代码只循环上面数组中的 4 个项目(但如果我将来增加这些 page_content_# 怎么办?)
foreach( $items_variable as $item_variable )
{
if (in_array($item_variable, array(
'page_content_1',
'page_content_2',
'page_content_3',
'page_content_4'
)))
{
if($item_variable == 'page_content_1') $order_in_page = 1;
if($item_variable == 'page_content_2') $order_in_page = 2;
if($item_variable == 'page_content_3') $order_in_page = 3;
if($item_variable == 'page_content_4') $order_in_page = 4;
....
}
}
我上面的当前方法对我来说看起来不太好,尤其是当涉及到这样的行时,
if($item_variable == 'page_content_1') $order_in_page = 1;
当我将来增加page_content_# 时,我会添加更多这样的行,我想脚本看起来会很丑。
如果我有其他类型的订单号数据(例如 - code_1、code_2 等)怎么办?然后我复制上面的代码并每次更改项目名称 - 这看起来很阴暗不是!
我怎样才能让它变得更好、更有活力?
【问题讨论】:
-
一般来说,忘记这些数字。您必须编写一个不需要任何此类数字并且可以处理任意数量的未来条目的解决方案,无论是 1 或 10 还是 1 千。
标签: php for-loop foreach php-5.3