fackz
fackz

Reputation: 531

Php inserting values into multi dimensional array

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

Category 2

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
        )

)

Upvotes: 0

Views: 50

Answers (2)

besciualex
besciualex

Reputation: 1892

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>";

Upvotes: 1

kainaw
kainaw

Reputation: 4334

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.

Upvotes: 1

Related Questions