doxn43207
2016-11-03 12:13 浏览 62
已采纳

如何从多维数组中删除数组?

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答 默认 最新

  • 已采纳
    dsla94915 dsla94915 2016-11-03 12:29

    Use array_filter with callback as

    $arr1 = array_filter($arr1, function ($var) {
        return $var['key'] != 'delete';
    });
    print_r($arr1);
    
    点赞 评论 复制链接分享
  • duanchui1279 duanchui1279 2016-11-03 12:19

    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.

    点赞 评论 复制链接分享

相关推荐