【问题标题】:PHP: improving the loop that uses foreach?PHP:改进使用 foreach 的循环?
【发布时间】: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_1code_2 等)怎么办?然后我复制上面的代码并每次更改项目名称 - 这看起来很阴暗不是!

我怎样才能让它变得更好、更有活力?

【问题讨论】:

  • 一般来说,忘记这些数字。您必须编写一个不需要任何此类数字并且可以处理任意数量的未来条目的解决方案,无论是 1 或 10 还是 1 千。

标签: php for-loop foreach php-5.3


【解决方案1】:

关联数组

你可以这样做:

$items_definitions = array(
    'page_content_1' => 1,
    'page_content_2' => 2,
    'page_content_3' => 3,
    'page_content_4' => 4,
    'page_content_5' => 5,
);

foreach( $items_variable as $item_variable ){ 
    if( isset( $items_definitions[ $item_variable])){
        $order_in_page = $items_definitions[ $item_variable];
    }
    ...
}

动态提取字符串的最后一部分

或者完全动态地假设它总是page_content_{$order_in_page},或者使用建议的hackartist regexp 或者使用“oldschool method”:

$prefix = 'page_content_';
foreach( $items_variable as $item_variable ){ 
    if( strncmp( $item_variable, $pregix, strlen( $prefix))){
        continue; // Assume that you don't want to do anything if it doesn't match
    }
    $page = intval( substr( $item_variable, strlen( $prefix)));
    if( !$page){
        continue;
    }
    $order_in_page = $page;
}

我建议从intval() 文档中学习示例:)

Switch声明

Php 提供了 switch 允许你用相对较少的代码处理许多不同的情况。

foreach( $items_variable as $item_variable ){
    switch( $item_variable){
        case 'page_content_1':
            $order_in_page = 1;
            break;
        case 'page_content_2':
            $order_in_page = 2;
            break;
        case 'page_content_3':
            $order_in_page = 3;
            break;
        ...
        default:
    }
}

但是,只有在前两个选项不适合您的情况下,我才会这样做(例如,您需要为每种情况调用不同的函数)。

【讨论】:

  • 感谢 Vyktor 的回答。
  • @lauthiamkok 我添加了一些关于 switch 语句的格式和信息,很高兴能提供帮助。
【解决方案2】:

不确定你到底想要什么,但试试这个而不是 if 语句:

preg_match('/page_content_([0-9]+)/',$item_variable,$matches);
$order_in_page = $matches[1];

【讨论】:

    【解决方案3】:

    我不确定我是否理解您的问题,但也许关联数组会是您的解决方案。您可以使用它将字符串与值匹配:

    $order_in_page = array(
        'page_content_1' => 1,
        'page_content_2' => 2,
        'page_content_3' => 3,
        'page_content_4' => 4,
        'someotherpage' => 5,
        'yet_another_page' => 6
    );
    
    
    $o = $order_in_page[$item_variable];
    

    关于数据结构的东西 http://en.wikipedia.org/wiki/Associative_array

    PHP 文档 http://php.net/manual/de/language.types.array.php

    【讨论】:

      【解决方案4】:

      如果您使用显式键将其写出,则您当前的数组如下所示:

      $items_variable = array(
          0 => 'page_id',
          1 => 'page_content_1',
          2 => 'page_content_2',
          3 => 'page_content_3',
          4 => 'page_content_4',
          ...
      );
      

      请注意,键编号与页面内容编号完全匹配。因此,您可以将foreach 循环更改为以下内容:

      foreach( $items_variable as $order_in_page => $item_variable )
      

      现在$order_in_page 应该与键号一起存储,在您的数组中,它与页面内容号直接相关。您可能需要将其转换为 int,尽管我不确定这个事实:

      $order_in_page = (int) $order_in_page;
      

      如果相反,您的数组如下所示(没有 'page_id' 元素):

      $items_variable = array(
          0 => 'page_content_1',
          1 => 'page_content_2',
          2 => 'page_content_3',
          3 => 'page_content_4',
          ...
      );
      

      做和上面一样的事情,但是在结果上加一:

      ++$order_in_page;
      

      如果需要强制转换,请在增量之前强制转换。

      【讨论】:

      • 谢谢,但如果我将page_content_# 移动到列表中的第三位,除非我像我一样保持他们的顺序上面的虚拟示例...
      • 在这种情况下,如果page_content_1 的键是2,那么下面的赋值应该起作用:--$order_in_page;(或者--((int) $order_in_page);,如果需要强制转换)。
      • 其实,忽略上面评论中的铸造说明。在递增或递减之前强制转换。
      【解决方案5】:
      foreach($items_variable as $item_variable) {   
          preg_match('/[0-9]*$/',$item_variable , $suffix);
          $suffix = $suffix[0];
          if ($suffix !== '') {
              # code 1
          } else {
              # code 2
          }
      }
      

      【讨论】:

        【解决方案6】:

        我不确定我是否理解您的问题,但您可能希望将数据存储在多维数组中,例如:

        $items_variable = array(
            'page_id',
            'content' => array(
                //content
            )
        );
        

        然后你可以遍历每个内容数组,例如:

        foreach($items_variable['content'] as $content) {
            //do stuff with the content
        }
        

        不需要正则表达式或其他东西。

        【讨论】:

          猜你喜欢
          • 2016-09-26
          • 2012-07-19
          • 1970-01-01
          • 1970-01-01
          • 2013-04-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-05
          相关资源
          最近更新 更多