PHP:改进使用 foreach 的循环?

发布于 2025-01-07 16:01:24 字数 1154 浏览 0 评论 0 原文

我使用 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 等)怎么办?然后我复制了上面的代码并每次都更改项目名称 - 这看起来相当令人沮丧不是!

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

I use foreach to loop the array below and then making the order number to be store in the database,

$items_variable = array(
    'page_id',
    'page_content_1',
    'page_content_2',
    'page_content_3',
    'page_content_4',
    ...
);

The code only loop 4 items from the array above (but what if I have these page_content_# increased in the future?)

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;
        ....
        }
}

The current method I have above doesn't look good to me especially when it comes to the line like this,

if($item_variable == 'page_content_1') $order_in_page = 1;

I will add more lines like this when I have page_content_# increased in the future and the script will look pretty ugly I suppose.

What if I have another type of data with order number (for instance - code_1, code_2, etc)? Then I have copy the code above and change the item name each time - this looks pretty gloomy isn't!

How can I make it better and dynamic?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

七秒鱼° 2025-01-14 16:01:24

关联数组

您可以这样做:

$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},或者使用正则表达式为 黑客建议或使用“老派方法”:

$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:
    }
}

然而,只有当前两个选项不适合你时我才会这样做(例如,你需要为每种情况调用不同的函数)。

Associative array

You can do this:

$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];
    }
    ...
}

Dynamically extracting last part of string

Or do it completely dynamically assuming that it's always page_content_{$order_in_page}, either with regexp as hackartist suggested or use "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;
}

I recommend studying examples from intval() documentation :)

Switch statement

Php provides switch which allows you to handle many different cases with relatively small amount of code.

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:
    }
}

I'd however do this only if first two options wouldn't work out for you (eg. you need to call different function for each case).

夜吻♂芭芘 2025-01-14 16:01:24

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

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

not sure exactly what you want but try this instead of the if statement:

preg_match('/page_content_([0-9]+)/',$item_variable,$matches);
$order_in_page = $matches[1];
小清晰的声音 2025-01-14 16:01:24

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

$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

I'm not sure I understand your question, but maybe an associative array would be a solution for you. You can use it to match a string to a value:

$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];

Stuff on the data structure
http://en.wikipedia.org/wiki/Associative_array

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

删除→记忆 2025-01-14 16:01:24

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

$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;

如果需要转换,请在增量之前进行转换。

Your current array, if you write it out with the explicit keys, looks like the following:

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

Notice that the key number matches completely with the page content number. Thus, you could change the foreach loop to the following:

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

Now $order_in_page should be stored with the key number, which in your array correlates directly to the page content number. You may need to cast it into an int, although I am not sure of this fact:

$order_in_page = (int) $order_in_page;

If instead, your array looked like the following (without the 'page_id' element):

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

Do the same thing as above, but add one to the result:

++$order_in_page;

If casting is needed, cast before the increment.

云醉月微眠 2025-01-14 16:01:24
foreach($items_variable as $item_variable) {   
    preg_match('/[0-9]*$/',$item_variable , $suffix);
    $suffix = $suffix[0];
    if ($suffix !== '') {
        # code 1
    } else {
        # code 2
    }
}
foreach($items_variable as $item_variable) {   
    preg_match('/[0-9]*$/',$item_variable , $suffix);
    $suffix = $suffix[0];
    if ($suffix !== '') {
        # code 1
    } else {
        # code 2
    }
}
无敌元气妹 2025-01-14 16:01:24

我不确定我理解你的问题,但你可能想将数据存储在多维数组中,例如:

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

然后你可以迭代每个内容数组,例如:

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

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

I'm not sure I understood your question, but you might want to store your data in a multidimensional array, like:

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

Then you could just iterate through each content-array, such as:

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

No need for regex or other stuff.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文