douxigai8757 2016-04-17 07:15
浏览 97
已采纳

带有嵌套foreach的PHP数组

I have a table with data from sql. Some of the columns in the db have more than 1 name. I have created an array from them but now I need to compare the two while creating a table.

$strArrayChildren = explode(',', $children);
$strArrayChildren = str_replace('and', '', $strArrayChildren);
$childCount = count($strArrayChildren);

$strArrayGrades = explode(',',$the_grades);
$strArrayGrades = str_replace('(', '', $strArrayGrades);
$strArrayGrades = str_replace(')', '', $strArrayGrades);

$grades ='';
foreach($strArrayChildren as $child){
    foreach($strArrayGrades as $grade){
       if(strpos($grade, $child) !== false){
            $grades = preg_replace('([a-z A-Z ()]+)', "", $grade);
        }elseif(strpos($grade, $child) !== true){
            $grades ='';
        }
   }
   echo "<tr>";
      echo "<td>{$child}</td>";
      echo "<td>{$last_name}</td>";
      echo "<td>Child</td>";
      echo "<td>{$grades}</td>";
   echo "</tr>";
 }

When I run this code I get the grade of the student to match with the first name from the array, but then the rest of the grades keep trying to match with the first student even though there is a new row with a new name.

Any help would be great! Thank you!

  • 写回答

1条回答 默认 最新

  • dssqq64884 2016-04-18 02:28
    关注

    I'm not sure about your database but this should work. I'm posting the response with static arrays.

    <?php
    $strArrayChildren = array("Becky"," Aaron"," Luke");
    $the_grades = "9 (Susan), 5 (Luke)";
    $strArrayGrades = explode(',',$the_grades);
    echo "<html><body><table style='text-align: center; width: 400px;'>";
    echo "<tr>";
              echo "<td>Child</td>";
              echo "<td>Grade</td>";
           echo "</tr>";
    foreach($strArrayChildren as $child){
        $grades = "";
        $child = trim($child);
        foreach($strArrayGrades as $key => $grade){
            if(strpos($grade, $child) > 0){
                $grades = intval(preg_replace('/[^0-9]+/', '', $grade), 10);
            }
       }
       echo "<tr>";
          echo "<td>{$child}</td>";
          echo "<td>{$grades}</td>";
       echo "</tr>";
     }
    echo "</table></body></html>";
    ?>
    

    Explanation:

    1. you need to initialize $grades right after first loop start
    2. There is no point to test both states of strpos() function
    3. It's safe to check position of needle occurrence in the string (be grater than 0)
    4. You need to change you regex for selecting numbers from an string.
    5. Trim needle in strpos(); there are unwanted white space in some cases. Better to trim white spaces at the start of the loop
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?