-1

こんにちは、私はこれを機能させることができないようで、8行目と11行目で未定義のエラーが発生し続けます.これが私のコードです

<?php
$count = 0;
$temp = 0;
$name = array("Suzuki", "Holden", "Jaguar", "Toyota", "Hyundai", "Ford", "Honda", "Mazda");
echo $name[0] . " " . $name[1] . " " . $name[2] . " " . $name[3] . " " . $name[4] . " " . $name[5] . " " . $name[6] . " " . $name[7] . "<p>";
for ($incount = 0; $incount <= 7; $incount++) {
    if ($name[$incount] > $name[$incount + 1]) {
        $temp = $name[$incount];
        $name[$incount] = $name[$incount + 1];
        $name[$incount + 1] = $temp;
        echo $name[0] . " " . $name[1] . " " . $name[2] . " " . $name[3] . " " . $name[4] . " " . $name[5] . " " . $name[6] . " " . $name[7] . $count++ . "<p>";
    }
}
?>
4

3 に答える 3

5

ここに間違いがあります:

$name[$incount] > $name[$incount + 1]

では、何が未定義なのか...7つの要素しか定義していないため$incount = 7...$incount +1 = 8

解決策は$incount < 7

于 2013-09-16T06:23:13.267 に答える
2

バブル ソートに正しいアルゴリズムを使用していません。2 つのループが必要です。

<?php
$count = 0;
$temp = 0;
$name = array("Suzuki", "Holden", "Jaguar", "Toyota", "Hyundai", "Ford", "Honda", "Mazda");
echo $name[0] . " " . $name[1] . " " . $name[2] . " " . $name[3] . " " . $name[4] . " " . $name[5] . " " . $name[6] . " " . $name[7] . "<p>";
for ($incount = 0; $incount <= 7; $incount++) {
    for ($innercount = $incount+1; $innercount <= 7; $innercount++) {
        if ($name[$incount] > $name[$innercount]) {
            $temp = $name[$incount];
            $name[$incount] = $name[$innercount];
            $name[$innercount] = $temp;
            echo $name[0] . " " . $name[1] . " " . $name[2] . " " . $name[3] . " " . $name[4] . " " . $name[5] . " " . $name[6] . " " . $name[7] . $count++ . "<p>";
        }
    }
}
?>
于 2013-09-16T06:36:06.487 に答える
-1
<?php
$count = 0;
$temp = 0;
$name = array("Suzuki", "Holden", "Jaguar", "Toyota", "Hyundai", "Ford", "Honda", "Mazda");
echo $name[0] . " " . $name[1] . " " . $name[2] . " " . $name[3] . " " . $name[4] . " " . $name[5] . " " . $name[6] . " " . $name[7] . "<p>";
for ($incount = 0; $incount < 8; $incount++) {
    if(isset($name[$incount + 1]))
    if ($name[$incount] > $name[$incount + 1]) {
        $temp = $name[$incount];
        $name[$incount] = $name[$incount + 1];
        $name[$incount + 1] = $temp;}
        echo $name[0] . " " . $name[1] . " " . $name[2] . " " . $name[3] . " " . $name[4] . " " . $name[5] . " " . $name[6] . " " . $name[7] . $count++ . "<p>";

}
?>

しかし、より良い使用

<?php
$count = 0;
$temp = 0;
$name = array("Suzuki", "Holden", "Jaguar", "Toyota", "Hyundai", "Ford", "Honda", "Mazda");
foreach($name as $f) echo $f." ";
echo "<p>";
for ($incount = 0; $incount < 8; $incount++) {
    if(isset($name[$incount + 1]))
    if ($name[$incount] > $name[$incount + 1]) {
        $temp = $name[$incount];
        $name[$incount] = $name[$incount + 1];
        $name[$incount + 1] = $temp;}
        foreach($name as $f) echo $f." ";
        echo  $count++ . "<p>";
}
?>
于 2013-09-16T06:29:43.650 に答える