0

Ok, I'm parsing a html file using simple_dom_html and everything works fine. What I'm trying to do is to insert the values into a multi dimensional array.

Here's my code:

foreach ($html->find('li[class="searchFacetDimension"]') as $filtros) {
    foreach($filtros->find('div[class="dimensionContainer"] h4') as $titulo){
            echo $titulo->plaintext . "<br>";
        foreach($filtros->find('div[class="dimensionContainer"] ul li a') as $link){
            echo $link->plaintext . "<br>";
        }
        echo "<br>";
    }
}

It outputs:

Category 1

  • sub 1

  • sub 2

Category 2

  • sub 1

What I'm trying to do is output it as an array, something like:

Array
(
    [0] => Array
        (
            [cat] => Category 1
            [subs] => Sub 1, Sub 2
        )

    [1] => Array
        (
            [cat] => Category 2
            [subs] => Sub 1
        )

)

2 Answers 2

1

Here is the code you need:

$result = array();
foreach ($html->find('li[class="searchFacetDimension"]') as $filtros) {
    $aux = array()
    foreach($filtros->find('div[class="dimensionContainer"] h4') as $titulo){
            //echo $titulo->plaintext . "<br>";
            $aux['cat'] = $titulo->plaintext;
        foreach($filtros->find('div[class="dimensionContainer"] ul li a') as $link){
            //echo $link->plaintext . "<br>";
            $aux['subs'][] = $link->plaintext;
        }
        //echo "<br>";
    }
    $aux['subs'] = implode(", ",$aux['subs']);
    $result[] = $aux;
}
echo "<pre>";
print_r($result);
echo "</pre>";
Sign up to request clarification or add additional context in comments.

Comments

1

You did all the hard work. All you have to do is make an array:

$array = array();
foreach ($html->find('li[class="searchFacetDimension"]') as $filtros) {
    foreach($filtros->find('div[class="dimensionContainer"] h4') as $titulo){
            $array[] = array('cat'=>$titulo->plaintext,'subs'=>'');
        foreach($filtros->find('div[class="dimensionContainer"] ul li a') as $link){
            if($array[sizeof($array)-1]['subs'] != '')
                $array[sizeof($array)-1]['subs'].= ', ';
            $array[sizeof($array)-1]['subs'].= $link->plaintext;
        }
    }
}
print_r($array);

Note: I did add in a little complication about only using the comma separator when subs is not empty. I made it verbose to make it very clear that is what I was doing.

1 Comment

Hey kainaw thanks for your help, you code worked great but the other solution came out first. I just want to thank you anyway!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.