如何在 PHP 循环中动态创建变量名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6359673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:08:16  来源:igfitidea点击:

How do I dynamically create the variable name in a PHP loop?

phploopsvariable-variables

提问by Matt Elhotiby

Ok so i have this php foreach loop

好的,所以我有这个 php foreach 循环

<?php foreach ($step_count->rows as $step) { ?>

and $step will be the step numbers 1, 2, 3, 4, 5 up to the total steps

和 $step 将是步骤编号 1, 2, 3, 4, 5 直到总步数

within the loop i a need to set the value of the images within the loop to standard_image_1 or whatever step there is...so for example

在循环中 ia 需要将循环中图像的值设置为 standard_image_1 或任何步骤......所以例如

<input value="<?php echo {$standard_image_"$step['number']"}; ?>" />

so basically i need the variable $standard_image_1 and so on depending on the steps but i dont know the correct syntax to do this

所以基本上我需要变量 $standard_image_1 等等,具体取决于步骤,但我不知道这样做的正确语法

回答by Chris Baker

Look at the docs for "variable variables" - http://php.net/manual/en/language.variables.variable.php

查看“变量变量”的文档 - http://php.net/manual/en/language.variables.variable.php

<?php echo ${'standard_image_'.$step['number']}; ?>

Here's a mock-up, using the details you've given: http://codepad.org/hQe56tEU

这是一个模型,使用您提供的详细信息:http: //codepad.org/hQe56tEU