-4

I've written a PHP function that reads in a file of orders and stores them into an array. When I load my web page, I am getting:

Notice: Undefined index: id on line 112 

which is the final $orders[$order['id']] = $order;

Here's my function code

function readOrders($filename)
{
    $arr = file($filename) or die('ERROR: Cannot find file');

    $delimiter = ',';

    // reading in customers from file and storing in array of customers
    foreach ($arr as $line) {

        $splitcontents = explode($delimiter, $line);

        $order = array();

        $orders['id'] = $splitcontents[1];
        $orders['isbn'] = $splitcontents[2];
        $orders['title'] = utf8_encode($splitcontents[3]);
        $orders['category'] = utf8_encode($splitcontents[4]);

        $orders[$order['id']] = $order;
    }
    return $orders;
}
devblack.exe
  • 428
  • 4
  • 17

1 Answers1

0

I think you mean to add $splitcontents values to $order within your loop over $arr, but you are adding those values to plural order $orders instead.

When you were doing $orders[$order['id']] = $order; your $order array was always empty so you got an undefined index of id on the line $orders[$order['id']] = $order;.

Also, another possible problem would be, if you keep it as $orders inside that loop after, on every iteration you would be overriding it

You also want to set $orders = array() above your loop.

Please see:

    function readOrders($filename)
    {
        $arr = file($filename) or die('ERROR: Cannot find file');

        $delimiter = ',';

        // reading in customers from file and storing in array of customers

        $orders = array(); //setup $orders as an array we can append to
        foreach ($arr as $line) {

            $splitcontents = explode($delimiter, $line);

            $order = array();

            //changed $orders to $order here.
            $order['id'] = $splitcontents[1];
            $order['isbn'] = $splitcontents[2];
            $order['title'] = utf8_encode($splitcontents[3]);
            $order['category'] = utf8_encode($splitcontents[4]);

            $orders[$order['id']] = $order;
        }
        return $orders;
    }
    
Ballard
  • 869
  • 11
  • 25