如何与PHP中的空数组进行比较-未定义的偏移量

时间:2018-12-01 20:19:37

标签: php arrays

我的桌子上有32种产品,但我只想显示其中3种。
为此,我生成了随机的唯一编号,因此我根据其ID显示产品。

如果数字是唯一的,我将其放入数组中,以便以后可以比较并跳过该数字(如果该数字已经存在),但是问题是数组最初是空的,因此我将随机生成的数字与NULL索引进行比较数组,因为它是空的,我认为这是问题所在,我该如何解决呢?

error

的屏幕截图

此外,我的代码效率很低而且很慢(业余程序员),有关如何优化代码的一些技巧?
我什至不知道我的逻辑是否正确,但是我在脑海中经历了几次,除了空数组之外,一切似乎还不错。

其中一些变量使用克罗地亚语,请不要在意我对代码的注释,希望对您有所帮助。

<?php

        for($i = 0; $i < 3; $i++) //display only 3 products
        {
            getRandomNum();
            getSQLdata();
            displayProduct(); 
        }

        function getRandomNum()
        {
            $nums = array();                 //empty array for comparing numbers
            $brojac = 0;                     //counter
            $random_num = mt_rand(1, 32);    //32 is the size of tab_unija
            for($j = 0; $j < 3; $j++)        //generate 3 random UNIQUE numbers
            {
                if($brojac > 1) break;  //line 83       //if counter greater than 1, random unique number is found, stop the loop
                if($random_num = $nums[$j]) continue;   //if random number is equal to index of array, it's not unique, skip that number - this is the error, array is empty at the start
                else                          
                {                                       //if random number isn't already in the array
                    $nums[$j] = $random_num;            //index of array is set to random number
                    $brojac++;                          //counter is 1 because unique number is found
                }
                $brojac = 0;                            //reset counter to 0 so new random numbers can get generated
                if($j == 2 && $brojac == 0) $j = 0;     //if the loop is at the end and counter is still at 0, random unique number isn't found, set j to 0 to run loop again
            }
        }

        function getSQLdata()
        {
            $sql = mysqli_query($connection, "SELECT * FROM tab_unija WHERE UnijaID = $random_num"); //Select a product where ID is equal to the random generated number
            $fetch_sql = mysqli_fetch_array($sql);
            $proizvodjac = $fetch_sql['Proizvodjac']; //Manufacturer
            $model = $fetch_sql['Model'];             //Model
            $slika = $fetch_sql['Slika'];             //Image
            $cijena = $fetch_sql['Cijena'];           //Price
        }

        function displayProduct()
        {
            echo
            "<div class=\"izdvojeno\">
            <img src=\"$slika\">
            <h3>$proizvodjac $model</h3>
            <h4>$cijena KN</h4>
            </div>";
        }

        ?>

0 个答案:

没有答案