返回给定键以外的所有数组元素 [英] Return all array elements except for a given key

查看:75
本文介绍了返回给定键以外的所有数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的方法,我只是想知道是否有一种干净而雄辩的方法来从关联数组中返回与给定键不匹配的所有值?

Simple one, I was just wondering if there is a clean and eloquent way of returning all values from an associative array that do not match a given key(s)?

$array = array('alpha' => 'apple', 'beta' => 'banana', 'gamma' => 'guava');

$alphaAndGamma = arrayExclude($array, array('alpha'));
$onlyBeta      = arrayExclude($array, array('alpha', 'gamma'));

function arrayExclude($array, Array $excludeKeys){
    foreach($array as $key => $value){
        if(!in_array($key, $excludeKeys)){
            $return[$key] = $value;
        }
    }
    return $return;
}

这就是我正在(打算)使用的,但是,有没有更清洁的实现,也许是我在手册中错过的一些东西?

This is what I'm (going to be) using, however, are there cleaner implementations, something I missed in the manual perhaps?

推荐答案

您可以 unset 值:

$alphaAndGamma = $array;
unset($alphaAndGamma['alpha']);

使其更清晰.您可以通过将数组分配给另一个变量来复制它.

或在函数中:

function arrayExclude($array, Array $excludeKeys){
    foreach($excludeKeys as $key){
        unset($array[$key]);
    }
    return $array;
}

这篇关于返回给定键以外的所有数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆