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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀