简体   繁体   English

php-foreach迭代对数组数组失败

[英]php- foreach iteration failed for array of arrays

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>

Simple starting code:简单的启动代码:

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

Fiddle .小提琴

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
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.请注意,您并不是真的想使用sizeof() ,因为它是count()的别名,您不应该在循环中真正使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM