EotS EotS - 7 months ago 11
PHP Question

PHP Multidimensional Array foreach - do not repeat common value

Here is my array:

$tabs = Array(
[0] => Array
(
[primaryTabID] => 001
[subtabID] =>
[parent_tab] =>
[primaryName] => Tab1
[subName] =>
[BStatus] =>
)

[1] => Array
(
[primaryTabID] => 002
[subtabID] => 013
[parent_tab] => 002
[primaryName] => Tab2
[subName] => SubTab2-1
[BStatus] => A
)

[2] => Array
(
[primaryTabID] => 003
[subtabID] => 015
[parent_tab] => 003
[primaryName] => Tab3
[subName] => SubTab3-1
[BStatus] => A
)

[3] => Array
(
[primaryTabID] => 003
[subtabID] => 016
[parent_tab] => 003
[primaryName] => Tab3
[subName] => Subtab3-2
[BStatus] => A
)
)


The output I'm looking for lists each Primary Tab name only once, and then if it has subtabs each one is listed after the primary tab, like this:

Output:

001 -> Tab1
002 -> Tab2
013 -> SubTab2-1
003 -> Tab3
015 -> SubTab3-1
016 -> SubTab3-2


The nesting of foreach statements and if-else has me completely befuddled.

Answer

Create your array like this...

$out = array();
foreach($tabs as $tab) {
    if(!empty($tab['primaryTabID']))
        $out[$tab['primaryTabID']]['main'] = $tab['primaryName'];           
    if($tab['primaryTabID'] == $tab['parent_tab'])
        $out[$tab['primaryTabID']][$tab['subtabID']] = $tab['subName'];
}
echo "<pre>";
var_dump($out);

Then, process it (output is the same with what you displayed above..

    foreach($out as $key => $tab) {
        if(count($tab) == 1) {
            echo $key . " -> " .$tab['main']."\n";
        } else {
            foreach($tab as $subKey => $sub) {
                if($subKey == "main")
                    echo $key . " -> " .$tab['main']."\n";
                else
                    echo "\t".$subKey . " -> " .$sub."\n";
            }
        }
    }

OUTPUT

001 -> Tab1
002 -> Tab2
    013 -> SubTab2-1
003 -> Tab3
    015 -> SubTab3-1
    016 -> Subtab3-2