I try to add product to the shopping cart but I have some problems with the loop logic.
This function should add new product and check if product id is already in the cart. If it is in the cart it should add 1 to existing product or the quantity selected by user.
Here is some code that I have:
function AddToCart($pid, $q)
{
$quantity = $q;
$product_id = $pid;
if (is_array($_SESSION['products']))
{
foreach($_SESSION['products'] as $key => $my_value)
{
if ($pid === $my_value['product_id'])
{
if ($quantity != 1)
{
$quantity = $my_value['quantity'] + $quantity;
$_SESSION['products'][$key]['quantity'] = $quantity;
}
else
{
$quantity = $my_value['quantity'] + 1;
$_SESSION['products'][$key]['quantity'] = $quantity;
}
}
else
{
$_SESSION['products'][] = array(
'product_id' => $product_id,
'quantity' => $quantity,
);
}
}
}
else
{
$_SESSION['products'][] = array(
'product_id' => $product_id,
'quantity' => $quantity,
);
}
}
the var_dump of the $_SESSION will be the following:
array(8) {
[0]=> array(2) { ["product_id"]=> int(4) ["quantity"]=> int(1) }
[1]=> array(2) { ["product_id"]=> int(10) ["quantity"]=> int(1) }
[2]=> array(2) { ["product_id"]=> int(11) ["quantity"]=> int(2) }
[3]=> array(2) { ["product_id"]=> int(11) ["quantity"]=> int(3) }
[4]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(2) }
[5]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(3) }
[6]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(4) }
[7]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(5) } }
Although I add only 4 products: id 4, 10, 11 and 12
function AddToCart($pid, $q){
if(!is_array($_SESSION['products'])){
$_SESSION['products'] = array();
}
foreach($_SESSION['products'] as $key=>$my_value){
if($pid === $my_value['product_id']){
$_SESSION['products'][$key]['quantity'] += $q;
return true;
}
}
$_SESSION['products'][] = array('product_id' => $pid,
'quantity' => $q);
return true;
}
Related
I am trying to convert an array formatted as the following:
object(Categories_store_tree)#519 (1) {
["list_of_sections":"Categories_store_tree":private]=> array(5) {
["id"]=> int(1)
["name"]=> string(11) "Main Store"
["parent_id"]=> NULL
["children"]=> array(2) {
[0]=> array(5) {
["id"]=> int(2)
["name"]=> string(4) "Food"
["parent_id"]=> int(1)
["children"]=> array(0) { }
}
[1]=> array(5) {
["id"]=> int(3)
["name"]=> string(14) "Electronics"
["parent_id"]=> int(1)
["children"]=> array(2) {
[0]=> array(5) {
["id"]=> int(4)
["name"]=> string(8) "Headphones"
["parent_id"]=> int(3)
["children"]=> array(0) { }
}
[1]=> array(5) {
["id"]=> int(5)
["name"]=> string(5) "Smartphones"
["parent_id"]=> int(3)
["children"]=> array(0) { }
}
}
}
}
}
}
To this structure of array:
object(Categories_store_tree)#964 (1) {
["list_of_sections":"Categories_store_tree":private]=> array(5) {
[0]=> array(4) {
["id"]=> int(1)
["name"]=> string(11) "Main Store"
["parent_id"]=> NULL
}
[1]=> array(4) {
["id"]=> int(2)
["name"]=> string(4) "Food"
["parent_id"]=> int(1)
}
[2]=> array(4) {
["id"]=> int(3)
["name"]=> string(14) "Electronics"
["parent_id"]=> int(1)
}
[3]=> array(4) {
["id"]=> int(4)
["name"]=> string(8) "Headphones"
["parent_id"]=> int(3)
}
[4]=> array(4) {
["id"]=> int(5)
["name"]=> string(5) "Smartphones"
["parent_id"]=> int(3)
}
}
}
Currently I am doing in manual but the idea is to make it automatic. I have tried with this code, but it returns an empty array, I have also tried with a function but I have been stuck for a couple of days and don't know what to do.
$clean_array = array();
$cont = 0;
foreach ( $new_tree as $key => $value ) {
if ( is_array( $value ) ) {
$cont++;
foreach ( $value as $key1 => $value1 ) {
if ( is_array( $value1 ) ) {
$cont++;
foreach ( $value1 as $key2 => $value2 ) {
$clean_array[$cont][$key2] = $value2;
}
} else {
$clean_array[$cont][$key1] = $value1;
}
}
} else {
$clean_array[$cont][$key] = $value;
}
}
Maybe you could try something like this.
Convert the object To an array:
function objectToArray($d) {
if (is_object($d))
$d = get_object_vars($d);
return is_array($d) ? array_map(__METHOD__, $d) : $d;
}
Then:
$arr = objectToArray($object);
print_r($arr);
Source
Basically i want to compare arrays inside a multidimensional array,
So i want to compare everyone with etc category 1 against each other, category 2 against earch other etc etc.
So what i really want to do is:
Compare every category against each other with this formula
versus - won = x
And then find out who has the lowest number and then update that last survivor from each category in the database (The winners)
Any ideas on how i can solve this the best?
$arr;
$stmt = $dbCon->prepare(" SELECT versus, won, imgId, category FROM rating_versus ");
$stmt->execute();
$stmt->bind_result($versus, $won, $imgId, $category);
while ($stmt->fetch()) {
$arr[] = array('category' => $category, 'id' => $imgId, 'versus' => $versus, 'won' => $won);
// echo $imgId . "<br> Versus: " . $versus . "<br> Won: " . $won . "<br> <br>";
}
$stmt->close();
This will output something like this
array(9) {
[0]=> array(4) { ["category"]=> int(1) ["id"]=> int(1) ["versus"]=> int(42) ["won"]=> int(21) }
[1]=> array(4) { ["category"]=> int(1) ["id"]=> int(5) ["versus"]=> int(47) ["won"]=> int(24) }
[2]=> array(4) { ["category"]=> int(1) ["id"]=> int(13) ["versus"]=> int(47) ["won"]=> int(23) }
[3]=> array(4) { ["category"]=> int(2) ["id"]=> int(2) ["versus"]=> int(45) ["won"]=> int(19) }
[4]=> array(4) { ["category"]=> int(2) ["id"]=> int(4) ["versus"]=> int(49) ["won"]=> int(25) }
[5]=> array(4) { ["category"]=> int(2) ["id"]=> int(7) ["versus"]=> int(44) ["won"]=> int(25) }
[6]=> array(4) { ["category"]=> int(3) ["id"]=> int(3) ["versus"]=> int(47) ["won"]=> int(29) }
[7]=> array(4) { ["category"]=> int(3) ["id"]=> int(6) ["versus"]=> int(50) ["won"]=> int(18) }
[8]=> array(4) { ["category"]=> int(3) ["id"]=> int(9) ["versus"]=> int(45) ["won"]=> int(24) }
}
To find the winner, you don't need to eliminate one by one, who has the lowest score.
Winner is who has the highest score.
So your code should be like following
$arr; $stmt = $dbCon->prepare(" SELECT versus, won, imgId, category FROM rating_versus ");
$stmt->execute();
$stmt->bind_result($versus, $won, $imgId, $category);
$winners=array();
while ($stmt->fetch()) {
$arr[] = array('category' => $category, 'id' => $imgId, 'versus' => $versus, 'won' => $won);
if(isset($winners[$category])) {
$curmax = $winners[$category]['won'];
if($won>$curmax) {
$winners[$category] = array('id'=>$imgId, 'won' => $won);
}
} else {
$winners[$category] = array('id'=>$imgId, 'won' => $won);
}
// echo $imgId . "<br> Versus: " . $versus . "<br> Won: " . $won . "<br> <br>";
}
$stmt->close();
print_r($winners);
This should work for this case
I have this foreach loop that outputs the below array, and I'm having a senior moment, I need it to return one array with no duplicate values, and I just can't it right.
foreach ( $post_groups as $post_group => $id ) {
group = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $table_name WHERE ID = %d", $id), ARRAY_A);
$groups[$group['group_name']] = $group['group_name'] = unserialize( $group['group_users'] );
}
output:
array(2) {
["Registered Users"]=>
array(1) {
[0]=>
string(1) "2"
}
["Admin Users"]=>
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
}
}
Cheers
I believe the following is what you're after. Simply merge the arrays together and then ensure the result is unique.
$userIds = [
'Registered Users' => array(1,2,3),
'Admin Users' => array(3,4,5),
];
$allUserIds = array_unique(call_user_func_array('array_merge', $userIds));
var_dump($userIds);
/*
array(2) {
["Registered Users"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
["Admin Users"]=>
array(3) {
[0]=>
int(3)
[1]=>
int(4)
[2]=>
int(5)
}
}
*/
var_dump($allUserIds);
/*
array(5) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[4]=>
int(4)
[5]=>
int(5)
}
*/
Use to php functions : array_unique(array_merge())
test code:
$userIds = array('RegisteredUsers' => array('A','a','b','B'),'AdminUsers' => array('C','c','B','d','a'));
$allUserIds = array_unique(array_merge($userIds['RegisteredUsers'], $userIds['AdminUsers']));
echo "<br><br>";
var_dump($userIds);
var_dump($allUserIds);
I have this array (i can't change it) :
array(3) {
[0]=>
array(8) {
["kampania"]=> string(6) "dasdas"
[0]=> string(6) "dasdas"
["300x250"]=> int(1)
[1]=> int(1)
["160x600"]=> int(2)
[2]=> int(2)
["728x90"]=> int(3)
[3]=> int(3)
}
[1]=>
array(8) {
["kampania"]=> string(12) "aaaaaaaaaaaa"
[0]=> string(12) "aaaaaaaaaaaa"
["300x250"]=> int(4)
[1]=> int(4)
["160x600"]=> int(5)
[2]=> int(5)
["728x90"]=> int(6)
[3]=> int(6)
}
[2]=>
array(8) {
["kampania"]=> string(20) "AAAAAAAAAAAAAAAAAAAA"
[0]=> string(20) "AAAAAAAAAAAAAAAAAAAA"
["300x250"]=> int(7)
[1]=> int(7)
["160x600"]=> int(8)
[2]=> int(8)
["728x90"]=> int(9)
[3]=> int(9)
}
}
As you can see, I got repeated values, because the array as the defined key and then an integer key.
How can I create a function which will remove the integer key and value from array and return a new array already "clean"
the result expect should be like this:
array(3) {
[0]=>
array(8) {
["kampania"]=> string(6) "dasdas"
["300x250"]=> int(1)
["160x600"]=> int(2)
["728x90"]=> int(3)
}
[1]=>
array(8) {
["kampania"]=> string(12) "aaaaaaaaaaaa"
["300x250"]=> int(4)
["160x600"]=> int(5)
["728x90"]=> int(6)
}
[2]=>
array(8) {
["kampania"]=> string(20) "AAAAAAAAAAAAAAAAAAAA"
["300x250"]=> int(7)
["160x600"]=> int(8)
["728x90"]=> int(9)
}
}
Thanks Guys! I'm really sorry for ask it , but I loose already so much time trying to fix it by myself
function unset_num_keys($array)
{
$array_out = array();
foreach($array AS $k => $v)
{
if(is_array($v)) //value is an array, so clean it
{
$array_out[$k] = unset_num_keys($v); //clean "child" arrays
}
elseif(!is_numeric($k))
{
$array_out[$k] = $v; // key is "safe"
}
}
return $array_out;
}
Then
$clean_array = unset_num_keys($old_array);
Loop threw the array and if the key(index) is numeric then remove that item from the array.
foreach($level1_array as &$arr){
foreach ($arr as $key => $value) {
if (is_int($key)) {
unset($arr[$key]);
}
}
}
Example
<?php
$level1_array = array(
array(
"smith",
"name" => "smith",
"20",
"age"=>20
),
array(
"smith",
"name" => "smith",
"20",
"age"=>20
),
array(
"smith",
"name" => "smith",
"20",
"age"=>20
),
);
foreach($level1_array as &$arr){
foreach ($arr as $key => $value) {
if (is_int($key)) {
unset($arr[$key]);
}
}
}
var_dump($level1_array);
?>
You can try this code:
//$data = $yourData;
$newData = array();
foreach($data as $v){
array_push($newData,array_flip($v));
}
I have the following array: (ordered by parent_id)
array(9) {
[1]=>
array(3) {
["name"]=>
string(6) "Tennis"
["parent_id"]=>
NULL
["depth"]=>
int(0)
}
[7]=>
array(3) {
["name"]=>
string(11) "TOP LEVEL 2"
["parent_id"]=>
NULL
["depth"]=>
int(0)
}
[8]=>
array(3) {
["name"]=>
string(11) "TOP LEVEL 3"
["parent_id"]=>
NULL
["depth"]=>
int(0)
}
[2]=>
array(3) {
["name"]=>
string(5) "Shoes"
["parent_id"]=>
string(1) "1"
["depth"]=>
int(1)
}
[3]=>
array(3) {
["name"]=>
string(5) "Women"
["parent_id"]=>
string(1) "2"
["depth"]=>
int(2)
}
[4]=>
array(3) {
["name"]=>
string(4) "Mens"
["parent_id"]=>
string(1) "2"
["depth"]=>
int(2)
}
[5]=>
array(3) {
["name"]=>
string(12) "Mens Running"
["parent_id"]=>
string(1) "4"
["depth"]=>
int(3)
}
[6]=>
array(3) {
["name"]=>
string(11) "Mens Tennis"
["parent_id"]=>
string(1) "4"
["depth"]=>
int(3)
}
[9]=>
array(3) {
["name"]=>
string(9) "2nd level"
["parent_id"]=>
string(1) "8"
["depth"]=>
int(1)
}
}
I want to sort it in a way that it can be used in a drop down menu. The format for a drop down menu is:
$categories[$CATEGORY_ID] = str_repeat(' ', $value['depth']).$value['name'];
The above array up top is sorted by parent_id where top levels have a parent_id of NULL.
I need to sort it in such a way that the array is in order. For example:
[1] => 'Tennis';
[2] => '  Shoes'
[3] => ' Womens'
[4] => ' Men'
[5] => ' Mens Running
[6] => ' Mens Tennis
[7] => 'TOP LEVEL 2'
[8] => 'TOP LEVEL 3'
[9] => ' 2nd level'
I tried this:
function get_all_categories_and_subcategories($parent_id = NULL, $depth = 0)
{
$categories = $this->get_all($parent_id, 10000, 0, 'parent_id');
if (!empty($categories))
{
$unique_parent_ids = array();
foreach($categories as $id => $value)
{
$categories[$id]['depth'] = $depth;
$unique_parent_ids[$id] = TRUE;
}
foreach(array_keys($unique_parent_ids) as $id)
{
$categories = array_replace($categories, $this->get_all_categories_and_subcategories($id, $depth + 1));
}
return $categories;
}
else
{
return $categories;
}
}
function sort_categories($categories)
{
usort($categories, array('Category','do_sort_categories'));
return $categories;
}
static function do_sort_categories($a, $b)
{
$al = strtolower($a['parent_id']);
$bl = strtolower($b['parent_id']);
if ($al == $bl) {
return 0;
}
return ($al > $bl) ? +1 : -1;
}
function get_all($parent_id = NULL, $limit=10000, $offset=0,$col='name',$order='asc')
{
$this->db->from('categories');
if (!$this->config->item('speed_up_search_queries'))
{
$this->db->order_by($col, $order);
}
if ($parent_id === NULL)
{
$this->db->where('parent_id IS NULL', null, false);
}
else if($parent_id)
{
$this->db->where('parent_id', $parent_id);
}
$this->db->limit($limit);
$this->db->offset($offset);
$return = array();
foreach($this->db->get()->result_array() as $result)
{
$return[$result['id']] = array('name' => $result['name'], 'parent_id' => $result['parent_id']);
}
return $return;
}
I don't have the possibility to test this code right now, but you could try something like this (and correct from my comments if needed).
Hope it would help a bit.
$objects = array();
// turn to array of objects to make sure our elements are passed by reference
foreach ($array as $k => $v) {
$node = new StdClass();
$node->id = $k;
$node->parent_id = $v['parent_id'];
$node->name = $v['name'];
$node->depth = $v['depth'];
$node->children = [];
$objects[$k] = $node;
}
// list dependencies parent -> children
foreach ($objects as $node)
{
$parent_id = $node->parent_id;
if ($parent_id !== null)
{
$object[$parent_id][] = $node;
}
}
// sort children of each node
foreach ($objects as $node)
{
usort($node->children, function($a, $b){
return $a->id < $b->id;
});
}
// clean the object list to make kind of a tree (we keep only root elements)
$sorted = array_filter($objects, function($node){
return $node->depth === 0;
});
// flatten recursively
function flatten_node(&$node) {
return array_merge([$node], flatten($node->children));
}
array_walk($sorted, 'flatten_node');
// $sorted is a sorted list of objects (not array as defined at the beginning).
// You could turn it back to array and remove the 'children' key that was
// only used for sorting purposes.