Sydcpt
Sydcpt

Reputation: 139

Remove records from multidimensional array

I am trying to remove records from a multidimensional array if certain criteria are met. The condition is that the element 'cap' should only have 'Capped' or Uncapped', if 'Other' is there, it should be removed from the array.

I have tried using Unset() but with no luck. It does not break the code, but it changes nothing. Output of the array:

[0] => Array
    (
        [name] => Club Name
        [speed] => Annual Membership
        [cap] => Other
        [s_description] => Short description
        [l_description] => Long description
    )

[1] => Array
    (
        [name] => 50\5Mbps Fibre with 250GB
        [speed] => Residential 50/5 Capped
        [cap] => Capped
        [s_description] => Short description
        [l_description] => Long description
    )

[2] => Array
    (
        [name] => FB-FP-B-V-50/5MBPS-400-24
        [speed] => Residential 50/5 Capped
        [cap] => Capped
        [s_description] => Short description
        [l_description] => Long description
    )

Code for removing the 'Other' record:

foreach ($product_details['cap'] as $key ->$val_test) {
    if ($val_test == "Other") {
        unset($product_details[$key]);
    }
}

I realise I may be doing something really stupid, but for something that should be fairly simple, it seems really difficult!

Thanks

Upvotes: 1

Views: 49

Answers (3)

Gary
Gary

Reputation: 2339

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");

$result=array_diff($a1,$a2);

Else you have to loop like above. There are other methods to map as well.

Upvotes: 1

Standej
Standej

Reputation: 753

My solution

foreach ($your_array as $element) {
    if ($element['cap'] == "Other") {
        continue;
    } else {
        $newarray[] = $element;
    }
}

Upvotes: 1

JParkinson1991
JParkinson1991

Reputation: 1286

Assuming your main array is stored under the variable: $product_details

Your code would be

foreach($product_details as $key => $product){
    if($product['cap'] == "Other"){
        unset($product_details[$key]);
    }
}

You cant loop over '$product_details['cap']' as that is part of your inner array. You must loop over your outer array then check the value of the inner array.

I hope this makes sense.

EDIT: On rereading of your question you could change your if statement to this to make it more open ended;

if($product['cap'] != "Capped" && $product['cap'] != "Uncapped"){

Upvotes: 1

Related Questions