简体   繁体   English

从mysqli_fetch_array添加值

[英]Add values from mysqli_fetch_array

I'm this is my first coding project from school. 我是这是我学校的第一个编码项目。 I have a task to check, whether two conditions are true and if they are, I have to count the occurrences. 我有一个任务要检查,两个条件是否成立,如果两个条件成立,我必须计算发生的次数。 I'm really stuck right now and I would appreciate every helpfull answer. 我现在真的很困,我会很感激每一个有用的答案。

So this is part of the code: 因此,这是代码的一部分:

$verbindung = mysqli_connect($server, $user, $pass, $database)
                    or die ($meldung);

    $driverID = $_POST['fahrer'];

    $datum_von = $_POST['date_von'];
    //Change Date Format
    $datum_von_new = date_format(new DateTime($datum_von), 'Y-m-d');

    $datum_bis = $_POST['date_bis'];
    //Change Date Format
    $datum_bis_new = date_format(new DateTime($datum_bis), 'Y-m-d');

    $sql = "SELECT drivers.forename, drivers.surname, results.positionOrder, races.name, races.date ";
    $sql.= "FROM drivers ";
    $sql.= "INNER JOIN results ON drivers.driverId = results.driverId ";
    $sql.= "INNER JOIN races ON results.raceId = races.raceId ";
    $sql.= "WHERE drivers.driverId = '$driverID' "; 
    $sql.= "AND races.date BETWEEN '$datum_von_new' ";
    $sql.= "AND '$datum_bis_new' ";
    $sql.= "AND results.positionOrder <= 10;"   

<table class="table table-striped">
        <thead class="thead-dark">  
            <tr>
              <th scope="col">Fahrername</th>
              <th scope="col">Streckenname</th>
              <th scope="col">Datum</th>
              <th scope="col">Platzierung</th>
              <th scope="col">Häufigkeit</th>
            </tr>
        </thead>


    $ergebnis = mysqli_query($verbindung, $sql);
    $countPosition = 0

    if ($ergebnis != False) {
                while($zeile = mysqli_fetch_array($ergebnis)) { 
                    echo "<tr>";
                    echo "<td>" . $zeile['forename'] . ' ' . $zeile['surname'] . "</td>";
                    echo "<td>" . $zeile['name'] . "</td>";
                    echo "<td>" . $zeile['date'] . "</td>";
                    echo "<td>" . $zeile['positionOrder'] . "</td>";
                    for($i = 0; $i<=sizeof($zeile); $i++) {
                        for($j = 0; $j <= sizeof ($zeile); $j++) {
                            if($zeile['name'][$i] == $zeile['name'][$j] && 
                            $zeile['positionOrder'][$i] == $zeile['positionOrder'][$j]) {
                                $countPosition += 1;
                                echo "<td>" . $countPosition . "</td>";
                        }
                    }
                } 
                    echo "</tr>";

            } else {
                echo mysqli_error($verbindung);
            }

            $result = mysqli_close($verbindung);

So my goal is to check, whether the name in line 1 is equal to the name in line 2 AND if the positionOrder in line1 is equal to posisitionOrder in line 2. If so, count how many times this is true. 因此,我的目标是检查第1行中的名称是否等于第2行中的名称,以及第1行中的positionOrder是否等于第2行中的posisitionOrder。如果是,则计算这是正确的次数。 Help is appreciated. 感谢帮助。 Thank you! 谢谢!

So, a few things. 所以,几件事。

  1. You're going to want to change <= to < in your for loop or else you're going to get an index out of bound exception. 您将要在for循环中将<=更改为< ,否则将使索引超出绑定异常。 See Should one use < or <= in a for loop 请参阅是否应在for循环中使用<或<=

  2. You could solve this much easier using MySql, unfortunately you haven't shared your SQL query so I'm not able to write this for you. 您可以使用MySql轻松解决此问题,很遗憾,您尚未共享SQL查询,因此我无法为您编写此代码。 But it would be some form of group by . 但这是某种形式的group by

  3. I noticed that you're doing $zeil['name'][$j] for a lot of things as compared to $zeil[$j]['name'] , which is odd to me since that means you have an array of each element, instead of an array of "objects" (sort of) with properties attached to them. 我注意到,与$zeil[$j]['name']相比,您正在做$zeil['name'][$j]很多事情,这对我来说很奇怪,因为这意味着您有一个数组而不是包含附加属性的“对象”(某种)数组。 This isn't common practice, but I will try to work with it none the less. 这不是常见的做法,但是我仍将尝试使用它。

Let's assume your array looks like this: 假设您的数组如下所示:

$zeil = [
    'name' => [
         'nathan',
         'raverx1',
         'someone',
         'nathan',
         'nathan',
         'nathan',
         'anyone',
         'nathan',
         'anyone',
    ],
    'positionOrder' => [
         4,
         7,
         9,
         4,
         4,
         4,
         7,
         4,
         7
    ]
];

You would need this code to accomplish your task: 您将需要以下代码来完成您的任务:

// Loop through your main array while tracking
// the current index in the variable $i.
// Since you're using sub arrays, we use them
// as the index. Which means the sub arrays
// have to be of identical size, else you will
// get an index out of bounds error.
for($i = 0; $i < sizeof($zeil['name']); $i++) {

    // We set this to an initial value of 1 since
    // it is the first occurrence.
    $occurrenceCount = 1;

    // Create local variables containing the current values.
    $name = $zeil['name'][$i];
    $positionOrder = $zeil['positionOrder'][$i];

    // Loop through all previous entries to
    // compare them to the current one.
    for($j = $i-1; $j > -1; $j--) {
        if (
            $zeil['name'][$j] == $name &&
            $zeil['positionOrder'][$j] == $positionOrder
        ) {
            $occurrenceCount += 1;
        }
    }

    // If multiple occurrences were found
    // for this entry, output them.
    if ($occurrenceCount > 1)
        echo 'Occurrence Count ('.$name.') : '.$occurrenceCount.PHP_EOL;
}

The output would look like: 输出如下所示:

Occurrence Count (nathan) : 2
Occurrence Count (nathan) : 3
Occurrence Count (nathan) : 4
Occurrence Count (nathan) : 5
Occurrence Count (anyone) : 2

A better way to do this, would be to store the number of occurrences for anything with higher than 1 occurrence in it's own array, and then print them out. 更好的方法是将出现次数大于1的任何事物的出现次数存储在其自己的数组中,然后将其打印出来。

$multipleOccurrences = [];

// Loop through your main array while tracking
// the current index in the variable $i.
// Since you're using sub arrays, we use them
// as the index. Which means the sub arrays
// have to be of identical size, else you will
// get an index out of bounds error.
for($i = 0; $i < sizeof($zeil['name']); $i++) {

    // We set this to an initial value of 1 since
    // it is the first occurrence.
    $occurrenceCount = 1;

    // Create local variable containing the current values.
    $name = $zeil['name'][$i];
    $positionOrder = $zeil['positionOrder'][$i];

    // Loop through all previous entries to
    // compare them to the current one.
    for($j = $i-1; $j > -1; $j--) {
        if (
            $zeil['name'][$j] == $name &&
            $zeil['positionOrder'][$j] == $positionOrder
        ) {
            $occurrenceCount += 1;
        }
    }

    // If multiple occurrences were found
    // for this entry, store them using $name as the key.
    if ($occurrenceCount > 1)
        $multipleOccurrences[$name] = $occurrenceCount;
}

// Print the occurrences.
echo 'All occurrences greater than \'1\''.PHP_EOL;
echo '--------------------------------'.PHP_EOL;
foreach ($multipleOccurrences as $name => $occurrenceCount) {
    echo 'Occurrences ('.$name.') : '. $occurrenceCount . PHP_EOL;
}

The output would look like this: 输出如下所示:

All occurrences greater than '1'
--------------------------------
Occurrences (nathan) : 5
Occurrences (anyone) : 2

Keep in mind, that there are a few things WRONG with your initial approach. 请记住,您的初始方法有些错误。

  1. You're not actually keeping track of the occurrences, since each iteration will also add all of the previous occurrences to the $occurrenceCount variable as well. 您实际上并没有跟踪事件的发生,因为每次迭代还将所有先前的事件也添加到$occurrenceCount变量中。

  2. The data structure you're using isn't particularly friendly to properly tracking the number of occurrences. 您正在使用的数据结构对正确跟踪出现次数并不是特别友好。 Storing sub arrays for the values is abnormal, a more common way would be something like: 为值存储子数组是异常的,更常见的方式是:

     $zeil = [ [ 'name' => 'nathan', 'positionOrder' => 4 ], [ 'name' => 'bob', 'positionOrder' => 10 ], . . . ]; 
  3. The way your data structure is built requires you to have identical number of indexes for both of your sub arrays. 数据结构的构建方式要求您为两个子数组拥有相同数量的索引。 Which can end up causing unwanted errors if you forget to have it be so. 如果您忘记这样做,最终可能会导致不必要的错误。

When you iterate over the results, you would want the current row being read compared with the last one you processed. 遍历结果时,您希望将当前行与最后处理的行进行比较。

for($i = 0; $i<=sizeof($zeile); $i++) {
    if($i != 0 && $zeile['name'][$i] == $zeile['name'][$i - 1] && 
        $zeile['positionOrder'][$i] == $zeile['positionOrder'][$i - 1]) {
        $countPosition += 1;
        echo "<td>" . $countPosition . "</td>";
    }
}

The above code will iterate over the rows only once but will always compare the last read row with the current one. 上面的代码仅对行进行一次迭代,但始终将最后读取的行与当前的行进行比较。 It will not check earlier rows (only the previous row). 它不会检查前几行(仅检查前一行)。 So this might not be the ideal solution you are looking for. 因此,这可能不是您想要的理想解决方案。 A better option might be to use group by option in MySQL SELECT . 更好的选择可能是在MySQL SELECT使用group by选项。 You might want to read the this: Mysql Tutorials - Group by 您可能需要阅读以下内容: Mysql Tutorials-Group by

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM