gpt4 book ai didi

php - OOP 问题停止 PHP 运行和 MySQL 数据数组检索问题

转载 作者:行者123 更新时间:2023-11-29 22:23:31 25 4
gpt4 key购买 nike

现在,StackOverflow 的使用帮助我解决了很多问题,但是在准备好之前我的代码还存在两个问题,任何想法都很棒,因为我目前正在尖叫:

首先,我使用以下方法尝试从 MySQL 数据库中提取数据,将其作为数字数组返回并按 ID 排序。那里有 2 项,无论我做什么,我只能显示 1 项(当表格填满更多时,我需要它显示所有数据):

$query = "SELECT * FROM batch ORDER by ID";
$result = $mysqli->query($query);

/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

?>

其次,有点偏离主题,但下面的代码是由 StackOverflow 用户给出的,但是我无法让它工作,他们已经将其调整为 OOP,这不是我熟悉的领域,无论我做什么纠正 $this->public/private 它仍然拒绝工作(代码的目的是在$userinput 会根据 $widgetBatches 数组检查最接近的匹配(即输入是 1100,最接近的是 1000),然后从输入中扣除(留下 100),并且该过程再次循环进行检查,这次返回 100 作为最接近,此过程将继续,直到 $userinput 达到 0 或负数:

<?php

$userinput = 10000; // Our magic variable - user input

$iterations = 0;

function Widget($userinput)
{
$this->iterations++;
$widgetRequested = $userinput;
$widgetBatches = array("250", "500", "1000", "2000");

echo "Iteration " . $iterations;
echo "<br/>";

echo "Widget requested: " . $widgetRequested;
echo "<br/>";

$closest = GetClosest($widgetBatches, $widgetRequested);
echo "Closest: " . $closest;
echo "<br/>";

$widgetRemaining = $widgetRequested - $closest;
echo "Remainder: " . $widgetRemaining;

echo "<hr/>";
if($widgetRemaining > 0)
{
Widget($widgetRemaining);
}
else
{
echo "The value is now below or equaling zero: " . $widgetRemaining . "!";
}
}

function GetClosest($array, $value)
{
$lowest = null;
foreach($array as $val)
{
if($lowest == null || abs($value - $lowest) > abs($val - $value))
{
$lowest = $val;
}
}
return $lowest;
}


?>

最佳答案

这个:

<?php

function Widget($input) {
$currentValue = $input; // Set internal variable from input (Think of this as an initial "remainder")
$i = 0;
$widgetBatches = [250, 500, 1000, 2000]; // Setup batch array

while ($currentValue > 0) { // While the remainder is more than 0
$i++;
echo "Iteration " . $i . "<br/>";
echo "Widget requested: " . $currentValue . "<br/>";
$closest = GetClosest($widgetBatches, $currentValue); // Find the closest value from batch array
echo "Closest: " . $closest . "<br/>";
$currentValue = $currentValue - $closest; // Work out new remainder
echo "Remainder: " . $currentValue . "<hr/>";
}

// Loop will exit when remainder is less than 0
echo "The value is now below or equaling zero: " . $currentValue . "!";
}

function GetClosest($array, $value) {
$result = null; // Innitialise the returned variable in case of failure
foreach($array as $val) { // For every array value, unless stopped
$result = $val; // Set result to current array value
if($value <= $result) break; // Stop foreach loop if value is less than or equal to result
}
return $result; // Return last result from Foreach loop
}

Widget(9000);

?>

希望这些评论有用...我比平时提供了更多细节...

关于php - OOP 问题停止 PHP 运行和 MySQL 数据数组检索问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30486915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com