简体   繁体   English

PHP-根据另一个变量的值将值分配给变量

[英]PHP - Attributing a value to a var depending on the value of another var

I'm trying to attribute a value to a var depending of its text value. 我试图根据其文本值将值赋给var。 I can't just attribute the numerical value directly (via my form) because i'm also saving in my database the text value. 我不能直接将数字值归因于(通过表单),因为我还将文本值保存在数据库中。

$section = $_POST['section']; // required
$page = $_POST['page']; // required

if ($_POST['page'] == 'Template') { $Code == '00'; }
elseif ($_POST['page'] == 'Menu') { $Code == '01'; }
elseif ($_POST['page'] == 'Home Page') { $Code == '02'; }
elseif ($_POST['page'] == 'About Us') { $Code == '03'; }
elseif ($_POST['page'] == 'Contact Us') { $Code == '04'; }

$Code_Page = $Code.''.$section;

Exemple, the code for the section 18 of the Home Page is 0218. 例如,主页第18节的代码是0218。

I don't understand why it doesn't work ? 我不明白为什么它不起作用? Only the second part is saved ($section), not the first 2 numbers. 仅保存第二部分($ section),而不保存前两个数字。

Thanks in advance 提前致谢

EDIT: Author has clarified what he is after now. 编辑:作者已经澄清了他现在是什么。 I've kept the original answer in as I feel it is a better solution. 我保留了原始答案,因为我认为这是一个更好的解决方案。

To define a variable in PHP, you use a single equals sign (=). 要在PHP中定义变量,请使用单个等号(=)。 You've used two equals signs (==) when defining $Code , which is a comparison operator . 在定义$ Code时 ,您已经使用了两个等号(==),这是一个比较运算符

Original answer: 原始答案:

I'm assuming that you wish to optimize this code. 我假设您希望优化此代码。 If so, I feel the best way to do so is to either create an array, or pull from the database you mentioned from. 如果是这样,我觉得最好的方法是创建一个数组,或者从您提到的数据库中提取数据。 Once you have the dataset in an array, you can do some simple checking: 将数据集放入数组后,可以执行一些简单的检查:

Static array method: 静态数组方法:

$pages = array('Template' => '00', 'Menu' => '01', 'Home Page' => '02', 'About Us' => '03', 'Contact' => '04');
if (in_array($_POST['Page'], $pages))
{
    //We have a match, deal with output here
    $Code_Page = $pages[$_POST['Page']].$section
}
else
{
    //Output an error message here, the page isn't in the array
}

add $Code declaration first 首先添加$Code声明

$section = $_POST['section']; // required
$page = $_POST['page']; // required
$Code = ''; // This was missing 

if ($_POST['page'] == 'Template') { $Code == '00'; }
elseif ($_POST['page'] == 'Menu') { $Code == '01'; }
elseif ($_POST['page'] == 'Home Page') { $Code == '02'; }
elseif ($_POST['page'] == 'About Us') { $Code == '03'; }
elseif ($_POST['page'] == 'Contact Us') { $Code == '04'; }

$Code_Page = $Code.''.$section;

It seems like the code you have provided gives you the code you are looking for the homepage of 0218. The only error I see is you are not assigning the $Code . 您提供的代码似乎为您提供了0218主页的$Code 。我看到的唯一错误是您没有分配$Code Your $Code == '02' should be $Code = '02' 您的$Code == '02'应该是$Code = '02'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM