PHP, nested arrays, urgent help required

PHP, nested arrays, urgent help required
0

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.

The RecursiveArrayIterator class
Using the RecursiveArrayIterator to traverse an unknown amount of sub arrays within the outer array. Note: This functionality is already provided by using the RecursiveIteratorIterator but is useful in understanding how to use the iterator when using for the first time as all the terminology does get rather confusing at first sight of SPL!

<?php
$myArray = array(
    0 => 'a',
    1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))),
    2 => 'b',
    3 => array('subA','subB','subC'),
    4 => 'c'
);

$iterator = new RecursiveArrayIterator($myArray);
iterator_apply($iterator, 'traverseStructure', array($iterator));

function traverseStructure($iterator) {
   
    while ( $iterator -> valid() ) {

        if ( $iterator -> hasChildren() ) {
       
            traverseStructure($iterator -> getChildren());
           
        }
        else {
            echo $iterator -> key() . ' : ' . $iterator -> current() .PHP_EOL;   
        }

        $iterator -> next();
    }
}
?>

The output from which is:
0 : a
0 : subA
1 : subB
0 : subsubA
1 : subsubB
0 : deepA
1 : deepB
2 : b
0 : subA
1 : subB
2 : subC
4 : c
1 Like

That data structure had to be built and not directly from a sql query. Super ugly structure.

foreach($validServices as $service){
    foreach($service as $service_characteristics){
          foreach($service_characteristics as $key => $value){
                echo "{$key}: {$value}\n";
          }
     }
}