Teejten Teejten - 1 year ago 74
PHP Question

Another Undefined Offset Error

I am returning the JSON in the correct formatting but I am getting a

Notice: Undefined offset 2

when I visit the page. I spent all last night trying to fix this and I can get the error to go away but then I only get one row of the data instead of all the data. I've tried to change the key names to numbers and still can't get it to work.

#part of a factory pattern thats called by getIt()
public function selectAll($where='')
$stmt = $this->dbc->prepare("SELECT * FROM {$where}");
$this->results = $stmt->fetchAll();
return $this;

$output = $work->getIt('person')->results();

for($i=0; $i<=count($output); $i++) {
$response['person'][$i] = [];
$response['person'][$i]['fname'] = $output[$i]['fname'];
$response['person'][$i]['lname'] = $output[$i]['lname'];

print_r(json_encode($response, JSON_PRETTY_PRINT));

This is the output:

"person": [
"fname": "mitthe",
"lname": "mormon"
"fname": "jambi",
"lname": "myeyes"
"fname": null,
"lname": null

Answer Source

Solution 1:

after this line:

for($i=0; $i<=count($output); $i++) {

just insert this line:

if(!array_key_exists($i, $output)) continue;

Solution 2:

just replace <= with < like this:

for($i=0; $i<count($output); $i++) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download