过滤关联数组以仅保留具有白名单键的元素[重复]

问题描述 投票:0回答:2

我有如下所示的数组。

$a = [
    [id] => 18162876
    [name] => phpuG4fhx
    [type] => Video
    [created] => 2016-02-11T16:55:54+00:00
    [updated] => 2016-02-11T16:55:54+00:00
    [duration] => 14.975
    [hashed_id] => uzyng792la
    [description] => 
    [progress] => 0
    [status] => queued
    [thumbnail] => Array
        (
            [url] => https://embed-ssl.wistia.com/deliveries/c2b1eb4bdf6f872fb9da416994973a5358b31868.jpg?image_crop_resized=200x120&video_still_time=7
            [width] => 200
            [height] => 120
        )

    [account_id] => 410090];

其中,我只需要填充

[hashed_id]
[thumbnail]

php arrays filtering associative-array whitelist
2个回答
2
投票

不完全确定你在问什么,但是......

如果要访问数组的元素,可以使用以下格式:

$array[$key]

对于您的示例,它将是:

$a['hashed_id']

如果你想过滤数组,使其只包含

hashed_id
thumbnail
那么你可以这样做:

$filteredArray = [];
$filteredArray['hashed_id'] = $a['hashed_id'];
$filteredArray['thumbnail'] = $a['thumbnail'];

然后你就有一个仅包含

hashed_id
thumbnail
的数组。

如果这回答了您的问题,那就太好了;如果不是,您可能想澄清在“过滤”数组后您要做什么。您的预期结果是什么?


2
投票
$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];

var_dump(array_filter($arr, function($k) {
    return ($k == 'a') || ($k == 'b');
}, ARRAY_FILTER_USE_KEY));

或使用:

如果您使用 PHP >= 5.6,您现在可以设置一个标志来过滤数组键而不是数组值:

$allowed = ['foo', 'bar'];
$filtered = array_filter(
    $my_array,
    function ($key) use ($allowed) {
        return in_array($key, $allowed);
    },
    ARRAY_FILTER_USE_KEY
);
© www.soinside.com 2019 - 2024. All rights reserved.