WGS
WGS

Reputation: 23

PHP: How to delete specific SubArray of an Array by multiple values to match?

Let's say I have an array like this one:

$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 ]
];

Now I would like to be able to delete from array by multiple values like this:

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

But my problem is I do not understand the logic how to achieve this. This is what I have

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;

}

Upvotes: 1

Views: 91

Answers (2)

u_mulder
u_mulder

Reputation: 54831

Ultra short array_filter version with array_diff_assoc:

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

Fiddle here.

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57131

A simple modification to your code can work. This starts off assuming that you can remove an element, then if any of the values don't match, then flag it as not matching (and stop looking)...

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;

}

Upvotes: 1

Related Questions