如何从数组中获取不匹配的元素

时间:2017-02-26 06:56:46

标签: php arrays

我有一个多维数组,假设它是$resultSet

现在,我想获得与特定密钥不匹配的所有其他元素

为了进行简单的数组搜索,我可以使用$key = array_search(40489, array_column($resultSet, 'playerId'));,但这会给我匹配的集合,但我需要不匹配的集合。除了为它做功能外,我怎么能以最简单的方式做到这一点呢?

详细
假设以下是数组:

Array
(
    [0] => Array
        (
            [id] => 33
            [playerId] => 17875
            [room] => e3724021
            [playerName] => Lunch
            [boardSize] => 4
            [lastPing] => 1488089513
        )

    [1] => Array
        (
            [id] => 34
            [playerId] => 22072
            [room] => e3724021
            [playerName] => Dinner
            [boardSize] => 4
            [lastPing] => 1488089536
        )

)

现在假设我正在使用playerId: 17875搜索数组,那么我应该找回包含[playerId] => 22072的整个数组。

1 个答案:

答案 0 :(得分:1)

您可以使用array_filter http://php.net/manual/en/function.array-filter.php

进行过滤

将其用作函数的示例。

<?php 

$resultSet = array(
  array("id" => 33,
        "playerId" => 17875,
        "room" => "e3724021",
        "playerName" => "Lunch",
        "boardSize" => 4,
        "lastPing" => 1488089513),
  array("id" => 34,
      "playerId" => 22072,
      "room" => "e3724021",
      "playerName" => "Dinner",
      "boardSize" => 4,
      "lastPing" => 1488089536)
);

function filterOut($arr, $key, $value) {
  return array_filter($arr, function ($v) use ($key,$value) {
    return $v[$key] !== $value;
  });
}


print_r(filterOut($resultSet, 'playerId', 17875));

// Array
// (
//     [1] => Array
//         (
//             [id] => 34
//             [playerId] => 22072
//             [room] => e3724021
//             [playerName] => Dinner
//             [boardSize] => 4
//             [lastPing] => 1488089536
//         )

// )