PHP - 如何在索引中按值取消数组索引

时间:2017-06-21 11:05:55

标签: php arrays

我有一个对象数组($ response),如下所示:

Array
(
    [0] => stdClass Object
        (
            [CardNumber] => 5897853070424xxx
            [CardHolderName] => P Stoltz
            [CardHolderContactNumber] => 
            [CardHolderEmailAddress] => 
            [CardExpiryDate] => 2017-09-01T00:00:00
            [CardHolderTypeID] => 2
            [LastUsedDate] => 2017-05-25T00:00:00
        )
    [1] => stdClass Object
        (
            [CardNumber] => 589785304326xxx
            [CardHolderName] => J Stoltz
            [CardHolderContactNumber] => 
            [CardHolderEmailAddress] => 
            [CardExpiryDate] => 2017-09-01T00:00:00
            [CardHolderTypeID] => 2
            [LastUsedDate] => 2017-05-25T00:00:00
        )

)

现在,我需要取消设置CardNumber所在的整个对象!=' 589785304326xxx'

我试过这个:

$cardnumber = '5897853070424xxx'; 
    foreach( $response as $res )
    {
        if($res->CardNumber != $cardnumber)
        {
            unset($res);
        }
    }

这没有任何作用。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

您尝试过的操作只会取消循环中的当前对象。您需要执行以下操作:

foreach($response as $key => $res) {
    if($res->CardNumber != $cardnumber) {
        unset($response[$key], $res);
        continue;
    }
}

答案 1 :(得分:-1)

在循环中使用unset()

例如:

unset('key value', 'your array name');