简体   繁体   中英

Dealing with multidimensional array with empty dimensions

When dealing with this array, notices are given each time the array is referenced until something is added to it. All of the output works as expected regardless.

A screenshot of the notices: http://imgur.com/75RGA

function create_round(&$arrTeam)
{
    $numTeams = 4;

    $used = array();

    for ($i = 0; $i < $numTeams; $i++) {
        if (!in_array($i, $used)) { //if i isnt already scheduled to play
            for ($u = $numTeams-1; $u > $i; $u--) {
                if (!in_array($u, $used) && !in_array($u, $arrTeam[$i]["games"])) { //if u isnt already scheduled to play and u hasnt been played by i before
                    $arrTeam[$i]["games"][sizeof($arrTeam[$i]["games"])] = $u;
                    $arrTeam[$u]["games"][sizeof($arrTeam[$u]["games"])] = $i;

                    $used[sizeof($used)] = $i;
                    $used[sizeof($used)] = $u;

                    echo($arrTeam[$i]["name"] . " VS " . $arrTeam[$u]["name"] . "<br>");
                    break;
                }
            }   
        }
    }

    var_dump($arrTeam);
}

function round_robin()
{
    $numTeams = 4;

    //Create array
    $arrTeam = array(
        $team = array(
            "name" => "",
            "games" => array()
        )
    );

    //TEMP ASSIGNING NAMES
    for ($i = 1; $i < $numTeams+1; $i++)
        $arrTeam[$i-1]["name"] = "Team $i"; 

    //Echo Round numbers
    for ($i = 1; $i < $numTeams; $i++) {
        echo("<br>Round $i<br>");
        create_round($arrTeam);
    }
}

round_robin();

Should notices just be disabled or is there a better way of dealing with this?

I tried padding it but the code ended up twice as long and very messy.

you're checking this one all over the place:

$arrTeam[$i]["games"]

without testing its existence. Change to:

if (isset($arrTeam[$i]["games"]) && ..more checking.. ) { ..do stuff.. }

or you can disable notices:

error_reporting(E_ALL ^ E_NOTICE);

EDITED:

do this once in round_robin() function:

instead of:

$numTeams = 4;

//Create array
$arrTeam = array(
    $team = array(
        "name" => "",
        "games" => array()
    )
);

do:

$numTeams = 4;
for($x=0;$x<$numTeams;$x++) {
   $arrTeam[$x] = array("name"=>"","games"=>array());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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