我正在向PO模块开发票。所以,让我们说发票里面有3种产品,
Product a => Vendor A
Product b => Vendor B
Product c => Vendor A
我有一个从angularJS传递给PHP的数组。
数组被称为
products
以下代码位于我的PHP页面
中$products = isset($post_data['products']) ? $post_data['products']:array();
if(count($products) > 0){
foreach($products as $v){
//following code is working, but it will create 3 new PO with
//the respective products. So if let's say there are 3 products, with 2 items with same vendor, and 1 with another vendor,
//it will insert 3 new PO. What I wanted is to create 1 PO with 2 items(same vendor), 1 another PO with different vendor
$param = array(
//po data to insert
);
$this->_model->add($param);
$insert_id = $this->db->insert_id();
$products_array = array(
//purchased product
);
$this->generic_model->add($products_array);
}
}
这是来自数组的var_dump结果,该结果传递给PHP页面(来自var_dump($ v))
array (size=3)
'id' => string '35'
'vendor' => string 'Vendor 1'
'vendor_id' => string '5'
array (size=3)
'id' => string '33'
'vendor' => string 'Vendor 2 '
'vendor_id' => string '7'
array (size=3)
'id' => string '34'
'vendor' => string 'Vendor 2 '
'vendor_id' => string '7'
从var_dump结果可以看出,有2个相同的供应商,即供应商2。
所以我的问题是,如何在我的PHP中从angularJS循环数组,然后基于同一个供应商“分组”它?因此,通过前面的示例,我如何使用以下数据将数据插入到我的数据库中
2 tables in my db, purchase_order and purchased_product
New PO with 2 items inside from Vendor 2, (1 purchase order row with 2 rows in purchased_product)
Another new PO with 1 item from Vendor 1, (1 purchase order row with 1 row in purchased_product)
已经处理了很长一段时间,仍然无法弄清楚如何进行数组循环..
谢谢.. :)
答案 0 :(得分:2)
您的代码示例没有说明从哪里获得PO 1
和PO 2
密钥,因此我无法将其包含在解决方案中。请随时更新您的问题以澄清这一点。
如上所述采用JSON结构并将其转换为"数组"如果指定了字符串值,您可以尝试以下操作:
<?php
// firstly, just some boilerplate for this example
$json = <<<JSON
[
{
"id": "35",
"vendor": "Vendor 1",
"vendor_id": "5"
},
{
"id": "33",
"vendor": "Vendor 2",
"vendor_id": "7"
},
{
"id": "34",
"vendor": "Vendor 2",
"vendor_id": "7"
}
]
JSON;
$data = json_decode($json, true);
// now we can start extracting and grouping data
// assuming you are using >= 5.5 here
// `array_column()` extracts the values of all
// sub-arrays with the `vendor` key into an array
$vendors = array_column($data, 'vendor');
// `array_count_values()` aggregates a count
// for each instance of each string in the array
// with the vendor as the key and a count as its corresponding value
$vendorCounts = array_count_values($vendors);
// map over the keys and values, creating an array
// of strings in the specified format
$vendorGroups = array_map(function ($vendor, $count) {
return sprintf('%d items from %s', $count, $vendor);
}, array_keys($vendorCounts), $vendorCounts);
print_r($vendorGroups);
这会产生:
Array
(
[0] => 1 items from Vendor 1
[1] => 2 items from Vendor 2
)
文档参考:
希望这会有所帮助:)