douzhenao6515 2017-03-13 01:22
浏览 58
已采纳

如何从foreach PHP获得第一个非空过滤值?

I have an array then i filtered the value and the result is null/empty.

How to determine first filtered value that non empty?

<?php

$items = array('a1a','bb2','o3e','two','three');

$i=0;

foreach($items as $item) {

    $item = str_replace('a1a','',$item); //filter remove
    $item = str_replace('bb2','',$item); //filter remove
    $item = str_replace('o3e','',$item); //filter remove

    //ITRY THIS BUT NOT WORK IF THE SECOND AND THIRD IS EMPTY/NULL TOO
    if($i==0) {
        if(empty($item)){
            //skip
        } else {
            //STATUS PUBLISH
        }

    } else { 
        //STATUS ATTACHMENT
    }

$i++;           
}
  • 写回答

1条回答 默认 最新

  • dtqpw68806 2017-03-13 01:35
    关注

    How to get first non empty filtered value from foreach PHP?

    If I understood correctly, you want the first item from they array $items that has not been emptied with your str_replace.

    If this is correct, here is how to proceed:

    <?php
    $items = array('a1a','bb2','o3e','two','three');
    
    $first = true;
    foreach($items as $item) {
        $itemOriginal = $item;
        $item = str_replace(['a1a', 'bb2', 'o3e'] ,'',$item); //filter remove
    
        if(!empty($item) && $first == true){
            $first = false;
            echo "status publish -> ".$itemOriginal."
    ";
        } else {
            echo "skip -> ".$itemOriginal."
    ";
        }
    }
    

    This will output:

    skip -> a1a
    skip -> bb2
    skip -> o3e
    status publish -> two
    skip -> three
    

    If this is not what you want, please clarify your question and add a comment so I can look at it again.

    Update:

    can value 'three' not skip? so i want to make wordpress publish using php from value foreach. the first value 'two' as publish and 'three' the next is as attachment

    <?php
    $items = array('a1a','bb2','o3e','two','three');
    
    $first = true;
    foreach($items as $item) {
        $itemOriginal = $item;
        $item = str_replace(['a1a', 'bb2', 'o3e'] ,'',$item); //filter remove
    
        if(!empty($item) && $first == true){
            $first = false;
            echo "status publish -> ".$itemOriginal."
    ";
        } elseif(!empty($item)) {
            $first = false;
            echo "status attachment -> ".$itemOriginal."
    ";
        } else {
            echo "skip -> ".$itemOriginal."
    ";
        }
    }
    

    will output:

    skip -> a1a
    skip -> bb2
    skip -> o3e
    status publish -> two
    status attachment -> three
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程