PHP 在数组中搜索多个键/值对

标签 php arrays multidimensional-array

我有一个数组列表(在这个例子中我使用的是手机)。我希望能够搜索多个键/值对并返回它的父数组索引。

例如,这是我的数组:

// $list_of_phones (array)
Array
(
    [0] => Array
        (
            [Manufacturer] => Apple
            [Model] => iPhone 3G 8GB
            [Carrier] => AT&T
        )

    [1] => Array
        (
            [Manufacturer] => Motorola
            [Model] => Droid X2
            [Carrier] => Verizon
        )
)

我希望能够执行以下操作:

// This is not a real function, just used for example purposes
$phone_id = multi_array_search( array('Manufacturer' => 'Motorola', 'Model' => 'Droid X2'), $list_of_phones );

// $phone_id should return '1', as this is the index of the result.

关于我可以或应该如何做到这一点有什么想法或建议吗?

最佳答案

也许这会有用:

  /**
   * Multi-array search
   *
   * @param array $array
   * @param array $search
   * @return array
   */
  function multi_array_search($array, $search)
  {

    // Create the result array
    $result = array();

    // Iterate over each array element
    foreach ($array as $key => $value)
    {

      // Iterate over each search condition
      foreach ($search as $k => $v)
      {

        // If the array element does not meet the search condition then continue to the next element
        if (!isset($value[$k]) || $value[$k] != $v)
        {
          continue 2;
        }

      }

      // Add the array element's key to the result array
      $result[] = $key;

    }

    // Return the result array
    return $result;

  }

  // Output the result
  print_r(multi_array_search($list_of_phones, array()));

  // Array ( [0] => 0 [1] => 1 )

  // Output the result
  print_r(multi_array_search($list_of_phones, array('Manufacturer' => 'Apple')));

  // Array ( [0] => 0 )

  // Output the result
  print_r(multi_array_search($list_of_phones, array('Manufacturer' => 'Apple', 'Model' => 'iPhone 6')));

  // Array ( )

如输出所示,此函数将返回一个包含所有键的数组,这些键的元素满足所有搜索条件。

关于PHP 在数组中搜索多个键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13923524/

相关文章:

php - 当我在那里使用 if else 时出现 mysql 错误

javascript - 如何在提交表单后查找在PHP中添加的Div的数量

java - 我需要编写一个程序来打印一副洗过的牌和一副排序过的牌

javascript - 显示数组中的特定对象值而不是单独显示?

php - 取消设置变量属性上的数组

javascript - 使用 for in 循环访问嵌套对象

php - Ajax responseText 和 echo 损坏,返回头文件内容

php - jQuery .ajax 将整个 JavaScript 数组传递给 PHP

php - PHP 中速记比较的动态计数

python - 具有分层列的数据框的 Pandas 数据框