doutan5844 2016-03-20 08:44
浏览 45
已采纳

选中框选项值已选中

How to check and find match a select box's value against a series of PHP arrays e.g

<select id="person" name="person">
<option value="jane">Jane</option>
<option value="julia">Julia</option>
</select>

PHP arrays

$person_1 = ["Id"=> "1", "name"=>"Jane", "age"=>"23" ]
$person_2 = ["Id"=> "2", "name"=>"Julia", "age"=>"29"]

If user select jane then check the value against these two arrays. If it matches with one print the age of that particular person.

  • 写回答

1条回答 默认 最新

  • drrw8672 2016-03-20 08:50
    关注

    Use a multi-dimensional array so you can loop through it to find the matching name.

    $people = [
        ["Id" => "1", "name"=>"Jane", "age"=>"23" ],
        ["Id" => "2", "name"=>"Julia", "age"=>"29"]
    ];
    
    foreach ($people as $person) {
        if ($person['name'] == $_POST['person']) {
            echo "Age is {$person['age']}";
            break;
        }
    }
    

    Any time you find yourself creating variables with numeric names like $person1 and $person2, it's a sure sign that you should be using an array to collect them all into a single variable.

    If there will be lots of people, it would be more efficient to make $people an associative array:

    $people = [
        "Jane" => ["Id" => "1", "name"=>"Jane", "age"=>"23" ],
        "Julia" => ["Id" => "2", "name"=>"Julia", "age"=>"29"]
    ];
    

    Then you don't need a loop, just do:

    $person = $people[$_POST['name']];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染