You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中如何根据另一变量值设置变量?编程新手求助

问题分析与解决

你的代码里有两个关键错误,导致$b_num无法正确赋值:

  1. 混淆赋值与比较运算符
    看这两行代码:

    if ($egg_type = 'Free Range')
    if ($egg_type = 'Barn')
    

    这里用的是单等号=,这是赋值操作——会直接把字符串'Free Range'或'Barn'覆盖到$egg_type上,而不是判断原始值是否匹配。这会打乱后续所有判断逻辑,最终让$b_num因为没有匹配到正确条件而保持未定义状态。

  2. 多个独立if语句冗余且易出错
    每个if都会独立执行,即使前面已经匹配到条件,后面的判断还是会继续运行,既没必要也可能引发意外问题。


修正方案一:修复运算符+改用elseif

把错误的=改成比较用的==,同时换成elseif,匹配到条件后就停止后续判断:

$egg_type = $row["egg_type"];

if ($egg_type == 'M/S Select Farm') {
    $b_num = '1';
} elseif ($egg_type == 'Free Range') {
    $b_num = '1';
} elseif ($egg_type == 'Barn') {
    $b_num = '2';
} elseif ($egg_type == 'Intensive') {
    $b_num = '3';
} elseif ($egg_type == 'Organic') {
    $b_num = '0';
} elseif ($egg_type == 'Brioche') {
    $b_num = '3';
}

修正方案二:数组映射(更简洁推荐)

这种固定值映射场景,用数组直接对应会更清晰,还能避免运算符错误:

$egg_type = $row["egg_type"];
$eggMap = [
    'M/S Select Farm' => '1',
    'Free Range' => '1',
    'Barn' => '2',
    'Intensive' => '3',
    'Organic' => '0',
    'Brioche' => '3'
];
// 可选:设置默认值,防止$egg_type不在映射列表里的情况
$b_num = $eggMap[$egg_type] ?? '默认值';

这样就能保证$b_num根据$egg_type正确赋值了。

内容的提问来源于stack exchange,提问作者Stuart Bird

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 13:10:31