0

Why do I get unidentified index errors when I use this function, the code that it outputs is what I want, but it's throwing errors into the page too?

if($result) {
    $jsonData = convert($result);
}

function convert($result) {
$i = 0;
    $intermediate = array();

    while($rows = mysqli_fetch_assoc($result)) {
        $key = $rows['POS'];
        $x = $i;
        $y = $rows['COUNT'];
        $intermediate[$key][] = array('x' => count($intermediate[$key]), 'y' => $y);
        $i++;
    }


   $output = array();

    foreach($intermediate as $key => $values) {
        $output[] = array(
            "key" => $key,
            'values' => $values
        );
    }

    return json_encode($output, JSON_NUMERIC_CHECK);

The data it returns is

[{"key":"OW1","values":[{"x":0,"y":4},{"x":1,"y":3},{"x":2,"y":2},{"x":3,"y":1},{"x":4,"y":1}]},{"key":"OW2","values":[{"x":0,"y":4},{"x":1,"y":2},{"x":2,"y":1},{"x":3,"y":3},{"x":4,"y":2}]},{"key":"OW3","values":[{"x":0,"y":4},{"x":1,"y":5},{"x":2,"y":1},{"x":3,"y":2},{"x":4,"y":1}]}]

And errors are these

Notice: Undefined index: OW1 in C:\wamp\www\multibar.html.php on line 24

Notice: Undefined index: OW2 in C:\wamp\www\multibar.html.php on line 24

Notice: Undefined index: OW3 in C:\wamp\www\multibar.html.php on line 24

Engl12
  • 139
  • 11

1 Answers1

0

The notice is thrown because your are appending elements to a not yet defined variable. In PHP this is not actualy a problem because PHP just cast the variables to whatever it needs.

To eliminate this notice be sure to initialise all your variables :

if (!isset($intermediate[$key])) $intermediate[$key] = array();
$intermediate[$key][] = array('x' => count($intermediate[$key]), 'y' => $y);
DarkBee
  • 16,592
  • 6
  • 46
  • 58