3

I have a multidimensional which is a dynamic array like :

Array
(
    [0] => Array
        (
            [key] => delete
            [label] => hi Delete
        )

    [1] => Array
        (
            [key] => edit
            [label] => hi Edit
        )

    [2] => Array
        (
            [key] => update
            [label] => hi update
        )

)

now i want to delete an array below from above multidimensional array:

Array
    (
        [key] => delete
        [label] => hi Delete
    )

finally i want an output like:

Array (

    [0] => Array
        (
            [key] => edit
            [label] => hi Edit
        )

    [1] => Array
        (
            [key] => update
            [label] => hi update
        )

)

For this i have tried, below is my code:

<?php
  $arr1 = array(array("key" => "delete", "label" => "hi Delete"),array("key" => "edit", "label" => "hi Edit"), array("key" => "update", "label" => "hi update"));
   $diff = array_diff_assoc($arr1, array("key" => "delete", "label" => "hi Delete"));
   print_r($diff);
?>

But i get full $arr1 in the output:

Array
(
    [0] => Array
        (
            [key] => delete
            [label] => hi Delete
        )

    [1] => Array
        (
            [key] => edit
            [label] => hi Edit
        )

    [2] => Array
        (
            [key] => update
            [label] => hi update
        )

)

how can i do this please help me

lazyCoder
  • 2,544
  • 3
  • 22
  • 41

2 Answers2

3

Use array_filter with callback as

$arr1 = array_filter($arr1, function ($var) {
    return $var['key'] != 'delete';
});
print_r($arr1);
Saty
  • 22,443
  • 7
  • 33
  • 51
  • but the order of index has not arranged properly, it delete the 0th index and starts array with 1index – lazyCoder Nov 03 '16 at 12:36
  • OP mentioned 1,000's of records and seems concerned about performance, using php's array_ functions are much slower than interating through the collection. – Stuart Nov 03 '16 at 12:36
  • 2
    @BunkerBoy then $arr1 = array_values($arr1); – L. Herrera Nov 03 '16 at 12:38
1

You should loop through the array and test for the key you want to remove, like so: (written blind so youll need to test it!)

<?php
foreach ($arr1 as $thisArrIndex=>$subArray)
{
    if ( $subArray['key'] == "delete" )
    {
        unset($arr1[$thisArrIndex]);
    }
}
?>

Suggested edit was to break out of the loop after finding the key. It seems OP may have multiple keys like this (in the multiple sub arrays) and so i chose not to break out of the loop here.

Stuart
  • 6,630
  • 2
  • 24
  • 40