搜索php多维数组并检索键值

时间:2016-06-01 17:43:25

标签: php multidimensional-array

我有这个$ order数组,并希望将数据存储在mysql数据库中。

我需要整理产品( [type] => physical )并将键值放在一个mysql表中,并放入其他类型( [type] =&gt其他两个表中的;折扣 [type] => shipping_fee )。

[cart] => Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [type] => physical
                    [name] => Apple iPhone
                    [quantity] => 2
                    [reference] => ABC61
                    [tax_amount] => 329
                    [unit_price] => 5490
                )

            [1] => Array
                (
                    [type] => shipping_fee
                    [name] => FedEx Express
                    [quantity] => 1
                    [reference] => SHIPPING
                    [tax_amount] => 58
                    [unit_price] => 290
                )

            [2] => Array
                (
                    [type] => physical
                    [name] => IBM Laptop
                    [quantity] => 1
                    [reference] => XYZ10
                    [tax_amount] => 700
                    [unit_price] => 8000
                )

            [3] => Array
                (
                    [type] => discount
                    [name] => Discount Coupon
                    [quantity] => 1
                    [reference] => DISCOUNT
                    [tax_amount] => 0
                    [unit_price] => -650
                )

        )
)

这样的东西,但我不知道如何正确搜索数组并检索兄弟键值:

if ([type] == 'physical') {
  get key values for [name] and [quantity] .. insert them into table products
} elseif ([type] == 'shipping_fee') {
  get key values for [name] and [quantity] .. insert them into table shipping
} elseif ([type] == 'discount') {
  get key values for [name] and [quantity] .. insert them into table discounts
}

2 个答案:

答案 0 :(得分:2)

以下是使用开关确定表名的一种方法:

foreach($order['cart']['items'] as $values) {
    switch($values['type']) {
        case 'physical':
            $table = 'products';
            break;
        case 'shipping_fee':
            $table = 'shipping';
            break;
        case 'discount':
            $table = 'discounts';
            break;
    }    
    $query = "INSERT INTO $table (name, quantity)
                     VALUES ({$values['name']}, {$values['quantity']})";
}

答案 1 :(得分:0)

这样的事情

$physical = array_filter($cart['items'],function($item){
    return $item['type'] == "physical";
});
foreach($physical as $item){
    //make your inserts
}

php中的 array_filter 函数接受一个数组,并为数组中的每个元素调用一个函数,并为每个评估为true的元素返回一个新数组。