通过数组排序以查找匹配项

时间:2012-10-05 13:21:54

标签: php arrays

我有两个像这样的数组

Array
(
    [0] => MYU_MP1
    [1] => 4cc00e5f580f00c2e54193fde7129608
    [2] => da8bbfdb40be0dc2b3312ca1037f994a
    [3] => d4cfaa8db24c4b81db506189360b6b99
)
Array
(
    [0] => MYU_SC1
    [1] => MYU_SC2
    [2] => MYU_SF1
    [3] => MYU_SC3
    [4] => MYU_AD1
    [5] => MYU_AD2
    [6] => MYU_AD3
    [7] => MYU_AD4
    [8] => MYU_RC1
    [9] => MYU_RC2
    [10] => MYU_RC3
    [11] => MYU_RC4
    [12] => MYU_RC5
    [13] => MYU_RC6
    [14] => MYU_RC7
    [15] => MYU_RC8
)

第一个别名为“可交付”而另一个为“不可交付” 和第三个数组

Array
(
    [d8df18561040f3d9bd9868f5c5aaa7c2] => Array
        (
            [rowid] => d8df18561040f3d9bd9868f5c5aaa7c2
            [id] => MYU_SC1
            [qty] => 1
            [price] => 500
            [name] => WAEC Scratch Card
            [service_image] => assets/img/waec.jpg
            [service_category] => scratch_cards
            [subtotal] => 500
        )

第三个数组是别名“cart_items”

    [f68964856a61092d9a2566d024a0ba28] => Array
        (
            [rowid] => f68964856a61092d9a2566d024a0ba28
            [id] => MYU_MP1
            [qty] => 1
            [price] => 210000
            [name] => Apple iPhone 5 16gb
            [service_image] => 
            [service_category] => mobile-phones
            [subtotal] => 210000
        )

我编写了一个函数,它应该遍历第三个数组,以确定第三个数组的“id”元素是否是第一个或第二个数组的成员

//sort through cart items
    foreach ($cart_items as $key => $item) {
        if(in_array($item['id'], $deliverables) && in_array($item['id'], $non_deliverables)) {
            $deliverable = TRUE;
            $non_deliverable = TRUE;
        }

        if(in_array($item['id'], $deliverables) && !in_array($item['id'], $non_deliverables)) {
            $deliverable = TRUE;
        }

        if(in_array($item['id'], $non_deliverables) && !in_array($item['id'], $deliverables)) {
            $non_deliverable = TRUE;
        }

        if($deliverable && $non_deliverable)
            $type = "both";
        if($non_deliverable)
            $type = "non-deliverable";
        if($deliverable)
            $type = "deliverable";
    }
    return $type;

但是当第三个数组在第一个和第二个数组中都匹配时,函数返回“可交付”。我做得不对吗?

2 个答案:

答案 0 :(得分:2)

function somefunction()
        foreach ($cart_items as $key => $item) {
            $deliverable = in_array($item['id'], $deliverables);
            $non_deliverable = in_array($item['id'], $non_deliverables);

            $type = "none";
            if ($deliverable && $non_deliverable) {
                $type = "both";
            } elseif ($deliverable && !$non_deliverable) {
                $type = "deliverable";
            } elseif (!$deliverable && $non_deliverable) {
                $type = "non-deliverable";
            }
        }
        return $type;
}

答案 1 :(得分:1)

你的排序顺序错了。 $ deliveryrable和$ non_deliverable的检查应该是最后一次。或者,您可以使用if-else-if-else结构。