2016-03-22 9 views
0

Ich möchte PHP verwenden, um das folgende Array zu einer gedruckten Ausgabe als solche zu machen.Parse conf Datei zu einem Baum PHP

Array 

(

    [relation] => Array 

     (

      [parent.item] => Array 

       (

        [0] => p0 

        [1] => p1 

       ) 



      [p0.item] => Array 

       (

        [0] => business 

        [1] => tourism 

       ) 

      [business.item] => Array 

       (

        [0] => X 

        [1] => Y 

       ) 


     ) 

Um

0 p0 
    + business 
    - 0 X 
    - 1 Y 

Dies ist ein Stück Code, die ich bisher auf meine Bedürfnisse gefunden und bearbeitet, aber ich kann meinen Kopf nicht umschlingen, wie es geht ...

function plotTree($arr, $indent=0, $mother_run=true){ 

if ($mother_run) { 

    // the beginning of plotTree. We're at rootlevel 

    echo "start\n"; 

} 

foreach ($arr as $key=>$value){ 

    // show the indents 

    echo str_repeat(" ", $indent); 

    if ($indent == 0) { 

     // this is a root node. no parents 

     echo "O "; 

    } elseif (is_array($value)){ 

     // this is a normal node. parents and children 

     echo "+ "; 

    } else { 

     // this is a leaf node. no children 

     echo "- "; 

    } 

    // show the actual node 

    echo $key . " (" . $value. ")" . "\n"; 

    if (is_array($value)) { 

     // this is what makes it recursive, rerun for childs 

     plotTree($value, ($indent+1), false); 

    } 

} 

if ($mother_run) { 

    echo "end\n"; 

} 

} 

// Parse with sections 

$ini_array = parse_ini_file("test.ini", true); 

file_put_contents('test.txt', print_r($ini_array,true)); 

plotTree($ini_array['relation']); 

Antwort

0

einen Blick auf diese ...

<?php 

    $sampleArray = array(); 

    $sampleArray["relation"]["parent.item"] = array("p0", "p1"); 
    $sampleArray["relation"]["p0.item"] = array("business", "tourism"); 
    $sampleArray["relation"]["business.item"] = array("x", "y"); 

    $value2 = $sampleArray["relation"]["parent.item"]; 
    foreach($value2 as $key3=>$value3){ 
     echo "$key3 $value3<br>"; 
     $types = $sampleArray["relation"][$value3.".item"]; 
     foreach($types as $type){ 
      echo " + $type<br>"; 
      $items = $sampleArray["relation"][$type.".item"]; 
      foreach($items as $index=>$item){ 
       echo " - $index $item<br>"; 
      } 

      echo "<p>"; 
     } 
    } 
?>