Undefined offset: 1 en Invalid argument supplied for foreach()

I use the following two methods to get a listing with services which should be grouped by service

public function get_services()
    $sql = "SELECT service_id
                 , service
                 , omschijving
                 , footnote
              FROM services
          ORDER BY service";
    $stmt = $this->pdo->query($sql);
    return $stmt->fetchAll();

public function get_services_prijzen()
    $sql = "SELECT service_id
                 , service_omschrijving
                 , service_prijs
              FROM services_prijzen
          ORDER BY service_id, service_omschrijving"
    $stmt    = $this->pdo->query($sql);
    $prijzen = $stmt->fetchAll();
    $prijzen = array();
    foreach ($prijzen as $row)
        if (!is_array($prijzen[$row['service_id']]))
            $prijzen[$row['service_id']] = array();
        $prijzen[$row['service_id']] = $row;
    return $prijzen;

And I have the following in the View:

<?php foreach ($services as $service): ?>
  <h2><?php echo $service['service']; ?></h2>
  <?php foreach ($prijzen[$service['service_id']] as $prijs): ?>
    <p><?php $prijs['service_omschrijving']; ?><span><?php $prijs['service_prijs']; ?></span></p>      
  <?php endforeach; ?> 
<?php endforeach; ?>

But I keep getting the error messages as in the subject:

Undefined offset: 1 en Invalid argument supplied for foreach() on Line 6

which is this:

<?php foreach ($prijzen[$service['service_id']] as $prijs): ?>

What am I doing wrong?

I’m pretty sure this is a problem.

Hi Dormilich. Thx for the reaction. So how should I structure it differently?

Thank you in advance

I see no need to restructure. I would start with deleting the overwriting statement.

Ok. I took the second statement out $prijzen = array();. But I still get the same 2 errors

question, what is the purpose of the foreach loop in get_services_prijzen()? if it’s just to get the service id as key in the array then better use PDO::FETCH_GROUP.

I need to get the service_id from the get_services method, because each service can have multiple sub services with prices

I’d say that works as planned.

Not sure if I can follow you :frowning: So what do I need to adjust?

PHP complains about the $prijzen variable, not $service, so I would suspect the get_services_prijzen() method to be at fault.

I can’t find it in the documentation, but I’ve seen mention that PHP can have problems with syntax like this

<?php foreach ($prijzen[$service['service_id']] as $prijs): ?>

try adding curly braces to force the parsing order

<?php foreach ($prijzen[{$service['service_id']}] as $prijs): ?>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.