Nested arrays: urgent help required

Hi.

I have an array like so:

$validServices = (array [29])
$validSerices[0] = (array [1])
$validServices[0][0] = stdClass [16]
$validServices[0][0]->service_id = (string [1]) 1
$validServices[0][0]->title = (string [10]) Management

$validServices[1] = (array [1])
$validServices[1][0] = stdClass [16]
$validServices[1][0]->service_id = (string [1]) 2
$validServices[0][0]->title = (string [7]) Systems

I want to loop over the services simply echoing to the screen (this is part of a website template) “title” so I end up with:
Management
Sysyems

The data is from a SQL table and I do not know, in advance, how many services there will be.

I’d appreciate some help with the code for that loop. A foreach, I’m guessing?

Cheers.

correct.

From the looks of your data, you need two of them, in fact:

foreach($validServices AS $key => $subarray) {
    foreach($subarray AS $innerkey => $row) {
        echo $row->title;
    }
}
1 Like

m_huntley,

Thank you so much for your quick response.

I have implemented that code and have “some” success. I am getting output of titles but not what I expected. I think I need to fill you in on some “outer” code.

The array I have given already should get services belonging to a specific area. I am getting a list of theses areas but underneath each area I am getting exactly the same list of services (using your code).

Here is some outer code:

  <?php foreach ($validVerticals as $validVertical) : ?>
    <div>
      <h6><?= $validVertical->title; ?></h6>
      <ul>
        <?php $validServices = $vertical_group->getServices($validVertical->vertical_id); ?>
        <?php foreach($validServices AS $key => $subarray) : ?>
          <?php foreach($subarray AS $innerkey => $row) : ?>
            <li><a href = "/service/display?service_id=<?= $row->service_id; ?>"><?= $row->title; ?></a></li>                        
          <?php endforeach; ?>
        <?php endforeach; ?>
      </ul>
    </div>
  <?php endforeach; ?>

The output this gives me is:
Vertical 1 ---------- Vertical 2
Service1------------Service1
Service2------------Service2
Service3------------Service3
Service4------------Service4

Each vertical should have different services under it.

Idaes?
Service4

m_hutley,

Sorry… it was a caching issue, I had built in some caching to stop repeated reading of the database but not implemented it correctly so it was always using the data from the first outer loop instead of getting it fresh each time.

SO, complete. Thanks again my friend. You’re a star.
Mike

1 Like

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