[英]Search php multidimensional array and retrieve key values
I have this $order array and want to store the data in a mysql database. 我有这个$ order数组,想将数据存储在mysql数据库中。
I need to sort out the products ( [type] => physical ) and put the key values in one mysql table, and put the other types ( [type] => discount and [type] => shipping_fee ) in two other tables. 我需要整理产品( [type] => physical )并将键值放在一个mysql表中,并将其他类型( [type] => discount和[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
)
)
)
Something like this, but I don't know how to properly search the array and retrive the sibling key values: 像这样,但是我不知道如何正确地搜索数组并检索同级键值:
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
}
Here's one way using a switch to determine table names: 这是使用开关确定表名称的一种方法:
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']})";
}
how about something like this 这样的事情怎么样
$physical = array_filter($cart['items'],function($item){
return $item['type'] == "physical";
});
foreach($physical as $item){
//make your inserts
}
The array_filter function in php takes an array, and a function that is called for each element in the array, and returns a new array for each element that evaluated as true. php中的array_filter函数接受一个数组,并为该数组中的每个元素调用一个函数,并为每个评估为true的元素返回一个新数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.