如何只保留数组中的特定数组键/值?

Ben*_*enn 8 php multidimensional-array

我有一个多维数组,我正在搜索特定的值.如果找到这些值,我需要使用这些值提取索引(创建新数组)并删除所有其他值.

array_intersect在php 5.3上运行良好,现在在5.4它抱怨注意:数组到字符串转换.

我发现array_intersect在5.4上有多维数组的问题. https://bugs.php.net/bug.php?id=60198

这是我正在搜索的$ options数组

Array (

    [index1] => html
    [index2] => html
    [index3] => slide
    [index4] => tab
    [index5] => Array
        (
            [0] => 123
        )

)
Run Code Online (Sandbox Code Playgroud)

适用于php 5.3.x的代码

$lookfor   = array('slide', 'tab');
$found     = array_intersect($options, $lookfor);


print_r($found);


Array
(
    [index3] => slide
    [index4] => tab
)
Run Code Online (Sandbox Code Playgroud)

但在5.4.x中,这会产生上述错误.

请问,如果没有循环,这将是另一种方法.并没有压制错误.

谢谢!

Tur*_*ako 17

$array = [
    'a' => 4,
    's' => 5,
    'd' => 6,
];
$onlyKeys = ['s','d'];

$filteredArray = array_filter($array, function($v) use ($onlyKeys) {
    return in_array($v, $onlyKeys);
}, ARRAY_FILTER_USE_KEY);

prinr_r($filteredArray); //  ['s' => 5, 'd' => 6]
Run Code Online (Sandbox Code Playgroud)

要按值过滤,请从参数列表中删除 ARRAY_FILTER_USE_KEY。

  • `function($v)` 具有误导性,因为 `$v` 暗示它引用一个值,但事实并非如此。它应该是“function($key)”。 (5认同)

Ama*_*ali 6

array_intersect()不是递归的。该函数假设数组只有一层深,并期望所有数组元素都是标量。当它找到一个非标量值,即一个子数组时,它会抛出一个通知。

文档中array_intersect()含糊地提到了这一点:

注意:两个元素被认为相等当且仅当: (string) $elem1 === (string) $elem2。换句话说:当字符串表示相同时。

我能想到的一种解决方案是使用array_filter()

$lookfor = array('html', 'slide');
$found   = array_filter($options, function($item) use ($lookfor) {
    return in_array($item, $lookfor);
});
Run Code Online (Sandbox Code Playgroud)

注意:这仍然执行循环,并不比简单的foreach. 事实上,foreach如果数组很大,它可能比 a 慢。我不知道你为什么要避免循环——我个人认为如果你只使用循环会更干净。

演示

我能想到的另一个解决方案是在使用之前删除子数组array_intersect()

<?php

$options = array(
    'index1' => 'html',
    'index2' => 'html',
    'index3' => 'slide',
    'index4' => 'tab',
    'index5' => array(123),
);

$lookfor = array('html', 'slide');
$scalars = array_filter($options,function ($item) { return !is_array($item); });
$found = array_intersect ($scalars, $lookfor);

print_r($found);
Run Code Online (Sandbox Code Playgroud)

演示


zwa*_*cky 5

你可以使用 array_filter()

$arr = array(
  'index1' => 'html',
  'index2' => 'html',
  'index3' => 'slide',
  'index4' => 'tab',
  'index5' => array(0 => 123),
);

$with = array('html', 'slide');
$res = array_filter($arr, function($val) use ($with) {
    return in_array($val, $with);
});
Run Code Online (Sandbox Code Playgroud)

这将返回 index1、index2 和 index3。

编辑:只需阅读您的评论,即您的数组将包含大量条目。array_filter当然会在它们上面循环一个条件并创建一个新数组。