How to iterate this array to match all possible connections - arrays

As a person that couldn't grasp recursion, I'm getting an array that has unlimited depth on parent <> child id links. This is a category list from an ecommerce platform (Shopee). And I'm trying to build a relationship list between all the categories and subcategories from the array below.
How to get this
Women's Clothing -> Tshirt -> Trending
-> Promotion
Shoes -> Hiking Shoe -> Winter Shoe
From the array below
$category = Array(
[0] => Array
(
[category_id] => 16
[parent_id] => 0
[category_name] => Women's Clothing
[has_children] => 1
)
[1] => Array
(
[category_id] => 18
[parent_id] => 16
[category_name] => Tshirt
[has_children] => 1
)
[2] => Array
(
[category_id] => 901
[parent_id] => 18
[category_name] => Trending
[has_children] => 0
)
[3] => Array
(
[category_id] => 23
[parent_id] => 0
[category_name] => Shoes
[has_children] => 1
)
[4] => Array
(
[category_id] => 100
[parent_id] => 23
[category_name] => Hiking Shoe
[has_children] => 1
)
[5] => Array
(
[category_id] => 120
[parent_id] => 100
[category_name] => Winter Shoe
[has_children] => 0
)
[6] => Array
(
[category_id] => 1400
[parent_id] => 18
[category_name] => Promotion
[has_children] => 0
)
)

You could first group the items by their parent key, and then perform a depth-first traversal through the data:
function dfs(&$childrenfor, $id, $path) {
if (isset($childrenfor[$id])) {
foreach($childrenfor[$id] as $item) {
yield from dfs($childrenfor, $item["category_id"], [...$path, $item["category_name"]]);
}
} else {
yield $path;
}
}
// first group the items by parent key
foreach ($category as $item) {
$childrenfor[$item["parent_id"]][] = $item;
}
// ...then use depth-first traversal to collect the root-to-leaf paths in the tree
$result = [...dfs($childrenfor, 0, [])];
The $result would have the following for your example data:
[
["Women's Clothing", "Tshirt", "Trending"],
["Women's Clothing", "Tshirt", "Promotion"],
["Shoes", "Hiking Shoe", "Winter Shoe"]
]
I guess you can take it from there to generate a format that suits you.

Related

How to Sum value according to other column value in cakephp

I'm cakephp learner and working on a project.
I have a problem. I did google but unable to find the right solution. I hope, I can find the solution here.
Here is My Code.
function getCompanySales(){
$model=ClassRegistry::init('Customer');
$modelcompany=ClassRegistry::init('Company');
$from = date("Y-m")."-01 00:00:00";
$days_in_month = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
$to = date("Y-m")."-".$days_in_month." 24:00:00";
$companyname=$modelcompany->find('all');
$companiessales=$model->find('all',array(
'conditions' => array(
"AND" =>array(
"Customer.created >=" => $from,
"Customer.created <=" => $to
)
),
'recursive'=>-1
)
);
return $companiessales;
} // Get Company list
and I'm getting result like
Array (
[0] => Array ( [Customer] => Array ( [gateway] => 10 [amount] => 349 ) )
[1] => Array ( [Customer] => Array ( [gateway] => 7 [amount] => 150 ) )
[2] => Array ( [Customer] => Array ( [gateway] => 13 [amount] => 349 ) )
[3] => Array ( [Customer] => Array ( [gateway] => 10 [amount] => 350 ) )
[4] => Array ( [Customer] => Array ( [gateway] => 7 [amount] => 100 ) )
[5] => Array ( [Customer] => Array ( [gateway] => 9 [amount] => 299 ) )
[6] => Array ( [Customer] => Array ( [gateway] => 7 [amount] => 249 ) )
[7] => Array ( [Customer] => Array ( [gateway] => 10 [amount] => 249 ) )
[8] => Array ( [Customer] => Array ( [gateway] => 7 [amount] => 299 ) )
[9] => Array ( [Customer] => Array ( [gateway] => 12 [amount] => 199 ) )
[10] => Array ( [Customer] => Array ( [gateway] => 7 [amount] => 150 ) ) )
But I want to Sum the Value with same gateway like
array(
[7] => 948 //sum of gateway 7
[9] => 299 //sum of gateway 9
[10] => 948 //sum of gateway 10
[12] => 199 //sum of gateway 12
[13] => 349 //sum of gateway 13
)
In another query =>
array(
[7] => company 1
[9] => company 2
[10] => company 3
[12] => company 4
[13] => company 5
)
I want a final result as
array(
[company1] => 948
[company1] => 299
[company1] => 948
[company1] => 199
[company1] => 349
)
Thanks for all your help. I'm sure I'll get the easy steps to resolve the issue.
Thanks for stackoverflow to give me ideas and find out an solutions.
I, first find the customer list by sum the amount and group by gateway by bellow code.
in the view use the custom helper to get the name by id. that's what , I was looking for.
$companiessales=$model->find('all',array(
'fields'=>array(
'SUM(amount) AS amount',
'gateway'
),
'group' => 'Customer.gateway',
'conditions' => array(
"AND" =>array(
"Customer.created >=" => $from,
"Customer.created <=" => $to
)
),
'recursive'=>-1
)
);
Here is the code to get the gateway name by id (which we are making primary id by grouping them)..
function getGatewayName($id){
$model=ClassRegistry::init('Gateway');
$companiess=$model->find('first',array(
'fields'=>array('fullname'),
'conditions'=>array(
'Gateway.id' => $id,
),
'recursive'=>-1
)
);
$name=$companiess['Gateway']['fullname'];
return $name;
} // Get Payment Gateway Name

Print variables Up value

The print_r returns the following value:
[cobrancas] => Array
(
[0] => stdClass Object
(
[id] => 749205
[nossonumero] => 3189028
[dataemissao] => 1395284400
[datavencimento] => 1395370800
[datapagamento] => 1395284400
[dias_vencidos] => 788
[mora] => 0.23225806451613
[multa] => 1.8
[valor] => 90.00
[valorpago] => 88.57
[valordesconto] => 0.00
[jurosmora] => 0.00
[banco] => 33
[agencia] => 1525
[dac_agencia] => 0
[conta] => 013000045
[dac_conta] => 2
[carteira] => 201
[nome_empresa] => STOCK MIDIA INF. LTDA
[cod_cedente] => 1640348
)
But as I know it gives me values ​​of up to [ 50 ] up. How do I know the print me just [VALOR ] above 100.00 ???
$Arr = count($cliente->cobrancas);

combine two php array for json encode

Presently m working with CakePhp..i got some problem with combining two array and prepare for a json encoded array.. i used array_merge() property but its not working.. how can i encoded both of these two array..
M doing like this :
return json_encode(array_merge ($product_list,$price_list));
i have two php array as follows :
array 1:
Array
(
[0] => Array
(
[PriceList] => Array
(
[price_id] => 2
[price_name] => abc
[date_time] => 2015-07-06 16:22:56
[dealer_type] => Dealer
[purpose] => dealer
[status] => ACTIVE
)
)
[1] => Array
(
[PriceList] => Array
(
[price_id] => 3
[price_name] => xyz
[date_time] => 2015-07-06 16:22:56
[dealer_type] => Dealer
[purpose] => dealer
[status] => ACTIVE
)
)
)
array 2:
Array
(
[0] => Array
(
[Product] => Array
(
[cat_id] => 1
[subcat_id] => 3
[brand_id] => 1
[p_code] => PP12567
[name] => akai
[model_no] =>
[specification] => color tv
[color] =>
[quality] =>
[size] =>
[p_unavail] => 1
[demo_avail] => 0
[brochure] =>
[status] => active
)
[ProductPrice] => Array
(
[id] => 154
[p_code] => PP12567
[price_id] => 1
[quantity] => 233
[purchase_price] => 344.00
[selling_price] => 44.00
[discount_price] => 33.00
[tax] => 5.00
[datetime] => 2015-07-23 15:47:11
)
[ProductSubCategory] => Array
(
[subcat_id] => 3
[cat_id] => 1
[subcat_name] => samsung
[status] => active
)
[ProductCategory] => Array
(
[cat_id] => 1
[cat_name] => Electronics
[cat_type] => Product
[status] => active
)
)
[1] => Array
(
[Product] => Array
(
[cat_id] => 1
[subcat_id] => 4
[brand_id] => 1
[p_code] => PBC-676767
[name] => music
[model_no] => 33
[specification] =>
[color] =>
[quality] =>
[size] =>
[p_unavail] => 0
[demo_avail] => 0
[brochure] =>
[status] => active
)
[ProductPrice] => Array
(
[id] => 156
[p_code] => PBC-676767
[price_id] => 1
[quantity] => 767
[purchase_price] => 54.00
[selling_price] => 55.00
[discount_price] => 22.00
[tax] => 3.00
[datetime] => 2015-07-23 15:47:11
)
[ProductSubCategory] => Array
(
[subcat_id] => 4
[cat_id] => 1
[subcat_name] => sony
[status] => active
)
[ProductCategory] => Array
(
[cat_id] => 1
[cat_name] => Electronics
[cat_type] => Product
[status] => active
)
)
)
how to combine these two array into one and encoded into a json array..
You have to use array_merge but not directly on array1 and array2:
$toEncodeArray = [array_merge ($array1[0], $array2[0])] ;
If you only want the associative array (without the wrapping array), simply do:
$toEncodeArray = array_merge ($array1[0], $array2[0]) ;

Saving data, how to apply data to all records?

How would i save the following;
I want the first 4 items to apply to all the "products to be saved", given that this data is at the top of my form and "global" to the products that get saved how would i tell cakephp to save it to each product or do i have to create a foreach loop and manually insert the data?
Global data to each product.
[discount_id] => 17
[range_id] => 21
[category_id] => 6
[user_id] => 104
Array
(
[Product] => Array
(
[discount_id] => 17
[range_id] => 21
[category_id] => 6
[user_id] => 104
[0] => Array
(
[product_code] => ffff
[colour] => red
[lead_time_weeks] =>
[description] =>
[height] => 11111
[width] => 22222
[depth] =>
[price] =>
[discount] => 50
[discounted_price] =>
[quantity] =>
)
[1] => Array
(
[product_code] => fgfgfggf
[colour] => red
[lead_time_weeks] =>
[description] =>
[height] => 123
[width] => 123
[depth] =>
[price] =>
[discount] => 50
[discounted_price] =>
[quantity] =>
)
)
)
Save method in controller
$this->Product->saveAll($this->request->data['Product']
I would personally use a foreach loop, saveAll is meant for saving associated data.
e.g.
foreach($this->request->data['Product'] as $product){
// Don't want to add the generic items
if(is_array($product)){
$newProduct = $this->Product->create();
$newProduct['Product'] = $product; // To save added them seperately
// Then add the generic items into the array
$newProduct['Product']['discount_id'] = $this->request->data['Product']['discount_id'];
etc...
$this->Product->save($newProduct);
}
}

CakePHP: Using the same layout

In my "CouponsController.php", I have the following 2 functions:
public function index() {
$this->set('coupons', $this->Coupon->find('all'));
}
public function restaurants() {
$this->set('coupons', $this->Coupon->findBycategory_id('1'));
$this->render("index");
}
Basically, I want index function to return all coupons, and restaurants to return just category 1 (but I want to use the same view file).
I end up getting this errror:
Notice (8): Undefined index: Coupon [APP/View/Coupons/index.ctp, line 16]
It's because of how the array is returned for each of them. Here is my VIEW file and the results for each page:
Coupons/index.ctp:
foreach ($coupons as $c) {
print_r($c);
}
INDEX function:
Array ( [Coupon] => Array ( [id] => 1 [vendor_id] => 1 [category_id] => 1 [title] => $10 For Whatever [price] => 10.00 [value] => 20.00 [start_at] => 2012-02-07 12:03:00 [end_at] => 2012-02-29 12:03:05 [details] => Test [terms] => Test [mini_views] => 0 [large_views] => 0 [created] => 2012-02-08 12:03:12 ) ) Array ( [Coupon] => Array ( [id] => 2 [vendor_id] => 2 [category_id] => 2 [title] => Test [price] => 100.00 [value] => 200.00 [start_at] => 0000-00-00 00:00:00 [end_at] => 0000-00-00 00:00:00 [details] => [terms] => [mini_views] => 0 [large_views] => 0 [created] => 2012-02-08 12:14:03 ) )
RESTAURANTS function:
Array ( [id] => 1 [vendor_id] => 1 [category_id] => 1 [title] => $10 For Whatever [price] => 10.00 [value] => 20.00 [start_at] => 2012-02-07 12:03:00 [end_at] => 2012-02-29 12:03:05 [details] => Test [terms] => Test [mini_views] => 0 [large_views] => 0 [created] => 2012-02-08 12:03:12 )
Well it's just how cakephp returns it, a turnaround would be
foreach ($coupons as $coupon) {
$c = $coupon;
if (isset($coupon["Coupon"])) { // if is set index in array ["Coupon"] {
$c = $coupon["Coupon"];
}
print_r($c);
}
or
public function restaurants() {
$params = array('conditions' => array('Coupon.category_id' => 1));
$this->set('coupons', $this->Coupon->find('all', $params));
$this->render("index");
}

Resources