通过PHP数组搜索并返回值的问题

时间:2018-12-14 18:29:12

标签: php

想知道如何在以下数组中搜索[law],然后只返回[fine]该法律?

    Array ( [0] => Array ( 
[law] => Unroadworthy Vehicle 
[fine] => 500 
[jail] => 0
[statute] => Any registered vehicle that is lacking headlights, taillights, windshields, has extensive damage, or deemed unsafe to operate, can be considered unroadworthy. Vehicles to do not return a registration shall also be considered unroadworthy. )
            [1] => Array ( 
[law] => Headlights Required 
[fine] => 500 
[jail] => 0 
[statute] => Failure to use headlights after dark or in poorly lit areas or roadways )

..(数组连续108个唯一项)

我要遍历并在下拉菜单中显示法律

echo "<select name=\"charge\">";
$strJsonFileContents = file_get_contents("./includes/laws.json");
$issue = json_decode($strJsonFileContents, true);
$arrlength = count($issue);
for ($x = 0; $x < $arrlength; $x++)
    {
    $law = $issue[$x][law];
    echo "<option name=\"law\" value=\"$law\">$law</option>";
    }
echo "</select><br><br>";

我实际上不打算做隐藏元素部分。

我想在json_decode中搜索[law]并返回[fine]

4 个答案:

答案 0 :(得分:0)

您的$ law变量没有预期值,您应该会收到如下错误:

  

使用不确定的恒定定律-假定为“定律”

echo "<select name=\"charge\">";
$strJsonFileContents = file_get_contents("./includes/laws.json");
$issue = json_decode($strJsonFileContents, true);
$arrlength = count($issue);
for ($x = 0; $x < $arrlength; $x++)
    {
    $law = $issue[$x]['law'];
    echo "<option name=\"law\" value=\"$law\">$law</option>";
    }
echo "</select><br><br>";

关于隐藏的[fine]元素,您可以查看此question并执行以下操作:

$('#mySelect').change(function(){
   var id = $(this).find(':selected')[0].id;
   $('#hiddenFineInput').val(id);
})

答案 1 :(得分:0)

有一个类似的问题与解决方案。请参阅下面的链接。 PHP search array in array

答案 2 :(得分:0)

如果您只需要通过罚款,那么这将起作用:

if (Input.GetKeyUp (KeyCode.LeftShift) 
    || Input.GetKeyUp (KeyCode.W)) 
{
     myAnimator.speed = 0f;
     myAnimator.Play("cshake",0,0f);
}

如果您需要通过法律和罚款,那么您需要使用一些JavaScript来存储json对象,侦听选择字段的更改,然后在更改罚款时将罚款添加到隐藏字段中循环遍历json对象,并根据选择的法则进行罚款。

答案 3 :(得分:0)

我当时想得太深了..看来这将实现我的追求。

$arrlength = count($issue);
for ($x = 0; $x < $arrlength; $x++) {
    if($issue[$x]['law'] == $law) { $fine = $issue[$x]['fine']; }
}
相关问题