Search code examples
phparraysforeachexplode

Array in Array Php Foreach


i have array in array foreach.

I did not add html codes into foreach. Just to show an example. I've been working for 2 hours. Please help me.

My array explode code;

string = "Deri Renk|kırmızı-siyah-beyaz-sarı-lacivert,kadife Renk|kırmızı-sarı";
$delimiters = Array(",",":","|","-");

$res = multiexplode($delimiters,$string);

foreach ($res as $val) {
echo $val;
};

My Array Output;

Array
(
[0] => Array
    (
        [0] => Array
            (
                [0] => Array
                    (
                        [0] => HEAD
                    )

                [1] => Array
                    (
                        [0] => item1
                        [1] => item2
                        [2] => item3
                        [3] => item4
                        [4] => item5
                    )

            )

    )

[1] => Array
    (
        [0] => Array
            (
                [0] => Array
                    (
                        [0] => HEAD 2
                    )

                [1] => Array
                    (
                        [0] => item1
                        [1] => item2
                    )
            )
    )
);

I want to print as follows. It's a simple operation, but I could not do it because php is a bit of information. ;

<div>
<h1>HEAD</h1>
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
</div>

<div>
<h1>HEAD</h1>
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
</div>

my multiexplode function this:

function multiexplode ($delimiters,$string) {
$ary = explode($delimiters[0],$string);
array_shift($delimiters);
if($delimiters != NULL) {
    foreach($ary as $key => $val) {
        $ary[$key] = multiexplode($delimiters, $val);
    }
}
return  $ary;
}

Solution

  • I've gone for the option of rewriting it so that it's simpler to use. This involves removing the need for the multiexplode() function and instead doing this specifically for the string format involved.

    So first break down by , then split this up to header and content.

    $input = "Deri Renk|kırmızı-siyah-beyaz-sarı-lacivert,kadife Renk|kırmızı-sarı";
    $list = explode(",", $input);
    $list1 = [];
    foreach( $list as $item )   {
        list($key,$data) = explode("|", $item);
        $list1[$key] = explode("-", $data);
    }
    
    foreach ( $list1 as $heading=>$out )  {
        echo "<div><h1>$heading</h1><ul>";
        echo "<li>".implode("</li><li>",$out)."</li>";
        echo "</ul></div>";
    }
    

    The output is...

    <div>
        <h1>Deri Renk</h1>
        <ul>
            <li>kırmızı</li>
            <li>siyah</li>
            <li>beyaz</li>
            <li>sarı</li>
            <li>lacivert</li>
        </ul>
    </div>
    <div>
        <h1>kadife Renk</h1>
        <ul>
            <li>kırmızı</li>
            <li>sarı</li>
        </ul>
    </div>