当数组中的某个值等于你的函数时回显

时间:2016-02-11 10:02:28

标签: php arrays

我有一个包含此数组的数组:

$autos[] = array(
        "auto" => "Audi A6",
        "Max snelheid" => "240 km/h",
        "Verbruik" => "1 op 12");

$autos[] = array(
        "auto" => "Porsche 911",
        "Max snelheid" => "290 km/h",
        "Verbruik" => "1 op 8");

在我的下方,我使用了一个回应这个的foreach。

 foreach ($autos as $cars => $arr){
    echo '<tr>';
        foreach($arr as $test => $data){
            echo '<td>'.$data.'</td>';
    }
    echo '</tr>';
 }

当此值为"Verbruik" => "1 op 11"时,如何回显某些内容? 如果第二个数字高于11,我必须回应#34;那是正确的&#34;。

所以例子是:

$autos[] = array(
    "auto" => "Fiat Panda",
    "Max snelheid" => "140 km/h",
    "Verbruik" => "1 op 11");

所以,当我在上面的代码时。我怎么能回应&#34;那是正确的&#34; ?

2 个答案:

答案 0 :(得分:1)

使用explode()函数来爆炸你的字符串&#34; 1 op 12&#34;到2个数字的数组,然后检查第二个数字是否大于11或任何你想要的。

foreach ($autos as $cars => $arr){
    echo '<tr>';
        foreach($arr as $test => $data){             
            echo '<td>'.$data." ";
            if($test == "Verbruik"){
              $temp = explode(" op ",$data);
              if($temp[1] > 11 ){
                  echo "correct "; // do whatever you want
              }  
            }
            echo '</td>';
    }
    echo '</tr>';
 }

答案 1 :(得分:0)

试试这个:

 foreach ($autos as $cars => $arr){
    echo '<tr>';
        foreach($arr as $test => $data){
            $numbers = explode(" op ", $data);
            if($test == 'Verbruik'){

                if((int) $numbers[1] >= 11)

                     echo '<td>'.$data." , That's correct!</td>";
            }

            else
                echo '<td>'.$data.'</td>';
    }
    echo '</tr>';
 }