Teejten
Teejten

Reputation: 70

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
        }
    ]
}

Upvotes: 0

Views: 31

Answers (2)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

You are getting that notice because the offset 2 really doesn't exist. The only reason you're looking for offset 2 is because of the loop condition <=count($output). The count is 2, so $i will be 0, 1, and then 2. You can avoid this a few different ways. Two are shown in the other answer. Another way is to use a foreach loop instead:

foreach ($output as $person) {
    $response['person'][] = ['fname' => $output['fname'], 'lname' => $output['lname']];
}

Upvotes: 1

T.Todua
T.Todua

Reputation: 56401

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

Upvotes: 1

Related Questions