2017-04-10 88 views
1

这应该很简单,但我没有得到预期的结果。浏览器或者列出数组中的所有元素(当我包含“!”运算符时)或者不列出任何元素(当我不包含“!”运算符时)。我只是想列出除一个元素之外的所有内容,或者仅列出一个元素。我无法上班。列出除关联数组之外的所有密钥

$features = array(
    'winter' => 'Beautiful arrangements for any occasion.', 
    'spring' => 'It must be spring! Delicate daffodils are here.', 
    'summer' => "It's summer, and we're in the pink.", 
    'autumn' => "Summer's over, but our flowers are still a riot of colors." 
    ); 

    <h1>Labeling Array Elements</h1> 
    <?php 
    foreach ($features as $feature) { 
    if(array_key_exists('autumn', $features)) { 
    continue; 
    } 
    echo "<p>$feature</p>"; 
    }  
    ?> 
+0

但逻辑可与索引阵列。我的小提琴:main.xfiddle.com/de5f2f17/index_array_conditional.php。 <?php。$ flowers = array('tulips','roses','daffodils','orchids','daisies'); ?> <?php foreach($ flowers AS $ flower){if($ flower =='daffodils'){ continue; }回声'

  • '。 ucfirst($ flower)。 '
  • ';如果($ flower =='orchids') {break; }}?> – Totsy

    回答

    2

    当你做对continue仅仅是因为它存在数组中的循环中,它停止在第一次循环。这总是如此。

    相反,你需要做的是这样的:你也可以使用array_filter这种方法

    foreach ($features as $season => $description) { 
        if ($season == 'autumn') { 
         continue; 
        } 
        echo $description; 
    } 
    
    -1

    $features = array(
        'winter' => 'Beautiful arrangements for any occasion.', 
        'autumn' => "Summer's over, but our flowers are still a riot of colors.", 
        'spring' => 'It must be spring! Delicate daffodils are here.', 
        'summer' => "It's summer, and we're in the pink.", 
    ); 
    
    print_r(array_filter($features, function ($key) { 
        return $key != 'autumn'; 
    }, ARRAY_FILTER_USE_KEY)); 
    

    现场演示:https://3v4l.org/Ctn8O

    相关问题