0

I have two arrays like given below

<?php
    $series = array 
    ( 
        0 => "Series A", 
        1 => "Series B", 
        2 => "Series C", 
        3 => "Series D", 
        4 => "Series E", 
        5 => "Series F" 
    );

    $episodes = array 
    ( 
        0 => array ( 0 => "a0" ), 
        1 => array ( 0 => "b0", 1 => "b1" ), 
        2 => array ( 0 => "c0", 1 => "c1" ), 
        3 => array ( 0 => "d0" ),
        4 => array ( 0 => "e0" ),
        5 => array ( 0 => "f0" ) 
    ); 
?>

What I'm trying to do is to link these two arrays so the output will look like this

Desired Output

Series A- a0
Series B- b0, b1
Series C- c0, c1
Series D- d0
Series E- e0
Series F- f0

To achieve this, I iterated the arrays like this but I'm not getting the desired output.

<ul>
    <?php 
        for($i=0; $i<sizeof($series); $i++)
        {
            foreach($episodes as $row => $innerArray){
                foreach($innerArray as $innerRow => $value){
                    $value = $value.', ';
                }
                echo "<li>".$series[$i]."-     ".$value."</li>";
            }

        }
    ?>
</ul>
2
  • How you sure about binding element in arrays with keys ? are length always same for both array ? Commented Dec 30, 2019 at 8:33
  • Yes, length will be same for both arrays @Rishi Raut Commented Dec 30, 2019 at 8:36

3 Answers 3

3

Simple starting code:

foreach ($series as $key => $value) {
    echo $value . ' - ' . implode(', ', $episodes[$key]) . PHP_EOL;
}

Fiddle.

Sign up to request clarification or add additional context in comments.

Comments

1

First you can combine your array and then you can iterate on single array instead of two arrays

$new = array_combine($series,$episodes);
foreach($new as $key=>$value){
    echo $key . ' - ' . implode(', ',$value).'<br>';
}

output :

Series A - a0
Series B - b0, b1
Series C - c0, c1
Series D - d0
Series E - e0
Series F - f0

Comments

0
foreach ($series as $sKey => $sValue) {
    print sprintf('%s- %s%s', $sValue, implode(', ', $episodes[$sKey]), PHP_EOL);
}

note that you don't really want to use sizeof(), because it's an alias for count() and you should not really use it inside a loop.

Comments

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.