如何查找包含特定键/值的数组的索引号


How to find the index number of an array that contains a certain key/value

(
    [1] => Array
        (
            [rules_properties_id] => 1
            [operator] => >=
            [value] => 2
            [function] => NumOrdersPlaced
            [rules_properties_params] => Array
                (
                    [num_days] => 30
                    [customer_id] => 5
                )
        )
    [2] => Array
        (
            [rules_properties_id] => 1
            [operator] => >=
            [value] => 5
            [function] => NumOrdersPlaced
            [rules_properties_params] => Array
                (
                    [num_days] => 90
                    [customer_id] => 5
                )
        )
    [3] => Array
        (
            [rules_properties_id] => 2
            [operator] => >
            [value] => 365
            [function] => CustAcctAge
            [rules_properties_params] => Array
                (
                    [customer_id] => 5
                )
        )
)

这是我从数据库中返回的数组的print_r。我需要找到包含名为 NumOrdersPlaced 的函数的子数组的索引号(预期结果为 2。唯一的方法是通过循环遍历数组和子数组并进行比较(如本答案所示)来做到这一点吗?还是有我不知道的更高效、更优雅(即单行)的功能?

不,在 PHP 中没有用于搜索多维数组的单行,期望您自己为它编写一个函数并将其用作一个衬:)

办法是:

  1. 将数据结构更改为有利于搜索操作的某种程度。 例如 XML 与 xpath
  2. 从问题创建数组时,请创建另一个数组,该数组的索引是函数名称,哪些值是指向原始数组子数组的指针
  3. 使用数据库执行该操作。它针对它进行了优化

在寻找"正确"方法时,您必须在搜索、插入、更新、删除操作、内存消耗和易用性的性能之间找到折衷方案。


当您要求PHP解决方案时,这里有一个示例,我将如何使用其他索引数组在PHP中执行此操作:(方法2.来自上面的列表

// we need two arrays now:
$data = array(); 
$index = array();
// imagine you loop through database query results
foreach($db_result as $record) {
    // create a copy of $record as the address
    // of record will contain the last(!) element agter foreach
    $item = $record;
    // store pointers to that array in data and index
    $data []= &$item;
    $index[$item->function] = &$item;
}

// here is your one liner
$found = isset($index['NumOrdersPlaced']) ? $index['NumOrdersPlaced'] : NULL;
// another index seach:
$found = isset($index['CustAcctAge']) ? $index['CustAcctAge'] : NULL;
// note there is no additonal loop. The cost is the 
// additional memory for $index