循环数组并删除项目

时间:2016-07-14 13:29:58

标签: php arrays

我需要帮助:) 我编写一个脚本代码,循环遍历数组内的数组,如果在XXX字段中没有值,则删除一个元素(为NULL)。 我的阵列是:

    Array ( 
[idCampaign] => 3 
[idIT] => 322 
     [recipients] =>Array ( 
        [0] => stdClass Object ( [name] => minnie  [email] => blabla@gmail.com [XXX] => ) 
        [1] => stdClass Object ( [name] => [email] => fddd@gmail.it [XXX] => 0.88451100 ) 
    ) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )

在此示例中,item [0]在XXX值中没有值,因此我的输出数组将为:

Array ( 
[idCampaign] => 3 
[idIT] => 322 
     [recipients] =>Array ( 
        [1] => stdClass Object ( [name] => [email] => fddd@gmail.it [XXX] => 0.88451100 ) 
    ) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )

我希望你能帮助我:)。

2 个答案:

答案 0 :(得分:1)

您可以使用嵌套的foreach()循环来遍历数据,然后执行一些测试,这些测试在失败时会保证取消设置相关变量是安全的。以下是:

<?php
    // WE SIMULATE SOME DATA TO POPULATE THE ARRAY, ONLY FOR TESTING PURPOSES
    $objDate        = new stdClass();       
    $objRez1        = new stdClass();
    $objRez2        = new stdClass();

    $objRez1->name  = "minnie";
    $objRez1->email = "blabla@gmail.com";
    $objRez1->XXX   = null;

    $objRez2->name  = null;
    $objRez2->email = "fddd@gmail.it";
    $objRez2->XXX   = 0.88451100;

    $objDate->sec   = 1468503103;
    $objDate->usec  = 0;

    // IN THE END WE NOW HAVE A SAMPLE ARRAY (SIMULATED) TO WORK WITH.
    $arrData        = array(
        'idCampaign'    => 3,
        'idIT'          => 322,
        'recipients'    => array(
            $objRez1,
            $objRez2
        ),
        'date'          =>$objDate,
    );


    // LOOP THROUGH THE ARRAY OF DATA THAT YOU HAVE
    // NOTICE THE &$data IN THE LOOP CONSTRUCT...
    // THIS IS NECESSARY FOR REFERENCING WHEN WE UNSET VARIABLES WITHIN THE LOOP
    foreach($arrData as $key=>&$data){
        // SINCE THE XXX KEY IS STORED IN THE 'recipients' ARRAY,
        // WE CHECK IF THE CURRENT KEY IS 'recipients' & THAT $data IS AN ARRAY
        if($key == "recipients" && is_array($data)){
            // NOW WE LOOP THROUGH THE DATA WHEREIN THE 'XXX' KEY LIVES
            foreach($data as $obj){
                // IF THE VALUE OF THE XXX KEY IS NULL OR NOT SET, 
                // WE SIMPLY UNSET IT...
                if(!$obj->XXX){
                    unset($obj->XXX);
                }
            }
        }
    }

    var_dump($arrData);

您可以验证结果HERE

希望这可以为您提供一些关于如何正确实施它的小提示......

答案 1 :(得分:0)

这应该做的工作

foreach($arrayOfObjects as $index => $object){
    if(!isset($object->xxx) || empty($object->xxx)){
        unset($arrayOfObjects[$index]);
    }
}