1
(
    [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
                )

        )

)

That's the print_r of an array that I'm getting back from my database. I need to find the index number of the sub-array that contains the function called NumOrdersPlaced (the expected result would be 2.) Is the only way to do this by looping through the array and subarrays and comparing (as in this answer)? Or is there a more efficient, elegant (i.e. one-liner) function available that I don't know about?

4

1 回答 1

0

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

方法是:

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

在搜索“正确”方式时,您必须在搜索、插入、更新、删除操作、内存消耗和易用性之间找到折衷。


当您要求使用 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
于 2013-01-30T17:31:10.320 回答