Teejten Teejten - 2 months ago 14
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}");
$stmt->execute();
$this->results = $stmt->fetchAll();
return $this;
}

#cheap-api.php
$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

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++) {