PHP.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET: 如何删除一个数组中特定的子数组,由多个值来匹配?

问题描述 投票:1回答:2

假设我有一个数组,就像这样。

$cart = [
  [ 'productID' => '11111' , 'size' => 'M' , 'quantity' => 2 ],
  [ 'productID' => '11111' , 'size' => 'L' , 'quantity' => 4 ],
  [ 'productID' => '22222' , 'size' => 'S' , 'quantity' => 3 ],
  [ 'productID' => '22222' , 'size' => 'L' , 'quantity' => 7 ],
  [ 'productID' => '33333' , 'size' => 'M' , 'quantity' => 1 ]
];

现在我希望能够从数组中删除多个值,就像这样。

removeElementFromArray( $cart , [ 'productID' => '11111' , 'size' => 'M' ] );

但我的问题是,我不明白如何实现这个功能的逻辑。我有以下的方法

function removeElementFromArray($targetArray=[],$needles=[]){

  foreach( $targetArray as $subKey => $subArray ){

    // This is wrong because $removeIt becomes TRUE by any needle matched
    // but I want it to become TRUE only if all $needles match.
    foreach( $needles as $key => $value ){
      if( $subArray[$key] == $value ){
        $removeIt = TRUE;
      }
    }

    // delete row from array
    if( $removeIt == TRUE ){ unset($targetArray[$subKey]); }

  }

  // return
  return $targetArray;

}
php arrays multidimensional-array key-value
2个回答
1
投票

简单修改一下你的代码就可以了。 首先假设你可以删除一个元素,然后如果任何一个值不匹配,则标记为不匹配(并停止寻找)。

function removeElementFromArray($targetArray=[],$needles=[]){

    foreach( $targetArray as $subKey => $subArray ){
        $removeIt = true;
        foreach( $needles as $key => $value ){
            if( $subArray[$key] !== $value ){
                $removeIt = false;
                break;
            }
        }

        // delete row from array
        if( $removeIt == TRUE ){ 
            unset($targetArray[$subKey]); 
        }

    }

    // return
    return $targetArray;

}

1
投票

超短 array_filter 版本有 array_diff_assoc:

function removeElementFromArray($targetArray, $needles) {
    return array_filter($targetArray, function ($item) use ($needles) {
        return !empty(array_diff_assoc($needles, $item));
    });
}

小提琴 此处.

© www.soinside.com 2019 - 2024. All rights reserved.