dream0776 2016-01-29 04:03
浏览 106
已采纳

从数组中删除与我定义的自定义值匹配的第一个键值对

I have array:

Array ( [0] => Array ( [0] => Apples [Query] => Apples ) [1] => Array ( [0] => Bananas [Query] => Bananas ) [2] => Array ( [0] => Bananas [Query] => Bananas ) [3] => Array ( [0] => Oranges [Query] => Oranges ) )

Unfortunately I have no control over the original structure of this array. So this is what we have to work with.

What I am trying to do is remove only the first key,value pair that matches a custom value that I define.

For Example:

$toRemove = 'Bananas';

Applied to a yet unknown miracle piece of code would result in:

Array ( [0] => Array ( [0] => Apples [Query] => Apples ) [2] => Array ( [0] => Bananas [Query] => Bananas ) [3] => Array ( [0] => Oranges [Query] => Oranges ) )

Notice how the second set of Bananas values remained untouched. I don't mind if you want to re-index because of gap this creates.

And if it wasn't challenging enough this needs to be done without a for loop.

  • 写回答

3条回答 默认 最新

  • douqi4673 2016-01-29 04:53
    关注

    ...this needs to be done without a for loop.

    If you don't want to use any kind of loop, then follow this recursive method:

    function removeElement(&$origArr, $arr, $element, $prevKey = null){
        static $flag = false;
        if($flag){
            return;
        }
        if(is_array(current($arr))){
            removeElement($origArr, next($arr), $element, key($arr));
        }else{
            if(current($arr) == $element){
                $flag = true;
                unset($origArr[$prevKey]);
                return;
            }else{
                removeElement($origArr, next($arr), $element, key($arr));
            }
        }
    }
    
    // suppose $arr is your original array
    removeElement($arr, $arr, 'Bananas');
    
    // display $arr array
    var_dump($arr);
    

    Output:

    array (size=3)
      0 => 
        array (size=2)
          0 => string 'Apples' (length=6)
          'Query' => string 'Apples' (length=6)
      2 => 
        array (size=2)
          0 => string 'Bananas' (length=7)
          'Query' => string 'Bananas' (length=7)
      3 => 
        array (size=2)
          0 => string 'Oranges' (length=7)
          'Query' => string 'Oranges' (length=7)
    

    Here are the relevant references:


    Later, if you want to rearrange the indices numerically then use array_values() function, like this:

    removeElement($arr, $arr, 'Bananas');
    
    $newArr = array_values($arr);
    var_dump($newArr);
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部