I have an array in session.
array(2) {
[0]=> array(5) {
["id"]=> string(1) "3"
["titulo"]=> string(25) "product 1"
["quantidade"]=> int(1)
["preco"]=> string(7) "1000.00"
["image"]=> string(15) "/img/no_img.png"
}
[1]=> array(5) {
["id"]=> string(1) "1"
["titulo"]=> string(43) "product 2"
["quantidade"]=> int(1)
["preco"]=> string(6) "157.20"
["image"]=> string(14) "produtos/1.jpg"
}
}
for example, if user add the same product again (eg: id 3), I'd like to add +1 in its quantity (quantidade) only.
I tried this, but products are always creating a new array, not updating the quantity.
Any ideas why?
if(!empty($_SESSION["cart_item"])) {
if(in_array($produto, array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($produto == $k) {
if(empty($_SESSION["cart_item"][$k]["quantidade"])) {
$_SESSION["cart_item"][$k]["quantidade"] = 1;
}
$_SESSION["cart_item"][$k]["quantidade"] += 1;
}
}
}
else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
}
else {
$_SESSION["cart_item"] = $itemArray;
}
$produto is the ID I'd like to update.
The $k variable contains the current array index [0,1,2,3], not the value of the current array id.
I'd try to compare your $producto with $_SESSION["cart_item"][$k]['id'] instead. I've also changed your condition to strictly compare both values ( === ) which is always a good idea.
One more things.
I'm not sure this line is relevent
if(in_array($produto, array_keys($_SESSION["cart_item"]))) {
You are trying to check if $produto is in the keys of $_SESSION["cart_item"]. However, the keys of $_SESSION["cart_item"] are the index that starts at 0. So the id 1 might not be at position 1.
You'd be better of using another variable ( lets say $dirty) to check if your current array was updated.
if(!empty($_SESSION["cart_item"])) {
$dirty = false;
foreach($_SESSION["cart_item"] as $k => $v) {
if($produto === $_SESSION["cart_item"][$k]['id']) {
$dirty = true
if(empty($_SESSION["cart_item"][$k]["quantidade"])) {
$_SESSION["cart_item"][$k]["quantidade"] = 1;
}
$_SESSION["cart_item"][$k]["quantidade"] += 1;
}
}
if(!$dirty) {
// the id was not present in the array
// we need to add it.
$_SESSION["cart_item"][] = [...];
}
}
else {
$_SESSION["cart_item"] = $itemArray;
}
Please note that this code is untested.
Related
I need some more help regarding PHP Arrays and the issue I am having. I have an array like this: -
array(2) {
[0]=>
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "100"
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
[1]=>
array(1) {
[0]=>
array(2) {
["count"]=>
string(3) "200"
["id"]=>
int(46)
}
}
}
However, I would like it to look more like this as array: -
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "300" <--- This has been added from Array 1 and 2
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
Basically if the same id is in both areas I want the count number to be added to each other but if it's not then it needs to just be left alone and included in the array.
I have used a number of array functions such as array_merge and array_push but I am running out of ideas of how this could work. I have also started working on a foreach with if statements but I just got myself completely confused. I just need a second pair of eyes to look at the issue and see howe it can be done.
Thanks again everyone.
Should work with something like this:
$idToCountArray = array(); //temporary array to store id => countSum
array_walk_recursive($inputArray, function($value,$key) { //walk each array in data structure
if(isset(value['id']) && isset($value['count'])) {
//we have found an entry with id and count:
if(!isset($idToCountArray[$value['id']])) {
//first count for id => create initial count
$idToCountArray[$value['id']] = intval($value['count']);
} else {
//n'th count for id => add count to sum
$idToCountArray[$value['id']] += intval($value['count']);
}
}
});
//build final structure:
$result = array();
foreach($idToCountArray as $id => $countSum) {
$result[] = array('id' => $id, 'count' => ''.$countSum);
}
Please note that I have not testet the code and there is probably a more elegant/performant solution.
You could use something like this:
$end_array = array();
function build_end_array($item, $key){
global $end_array;
if (is_array($item)){
if( isset($item["id"])){
if(isset($end_array[$item["id"]]))
$end_array[$item["id"]] = $end_array[$item["id"]] + $item["count"]*1;
else
$end_array[$item["id"]] = $item["count"]*1;
}
else {
array_walk($item, 'build_end_array');
}
}
}
array_walk($start_array, 'build_end_array');
Here is a fiddle.
Thank you ever so much everyone. I actually worked it by doing this: -
$fullArray = array_merge($live, $archive);
$array = array();
foreach($fullArray as $key=>$value) {
$id = $value['id'];
$array[$id][] = $value['count'];
}
$result = array();
foreach($array as $key=>$value) {
$result[] = array('id' => $key, 'count' => array_sum($value));
}
return $result;
this is my array:
$array= array(3) {
[0]=> array(3) { ["name"]=> "one" ["com"]=> "com1" ["id"]=> "1" }
[1]=> array(3) { ["name"]=> "two" ["com"]=> "com2" ["id"]=> "2" }
[2]=> array(3) { ["name"]=> "three" ["com"]=> "com3" ["id"]=> "3" }
I need posibility to change values of name and com for specific id. I try some examples from Stack questions:
1.Link1
foreach($array as &$value){
if($value['id'] == 1){
$value['name'] = 'test';
$value['com'] = 'test';
break; // Stop the loop after we've found the item
}
}
But it don't work. no error but no result too.
2.Link 2
Again,no error message,but no result...
I also try a lot of other examples from Stack but fake,and finaly to write a question..
Buy,
P
Since you are not changing your array value that's why it's-not giving you desired output. Try this:-
foreach($array as $key => &$value){
if($key == 1){
$array[1]['name'] = 'test';// change value to original array
$array[1]['com'] = 'test'; //change value to original array
break; // Stop the loop after we've found the item
}
}
for($i=0;$i<count($array);$i++) {
if($array[$i]['id'] == 1) {
$array[$i]['name'] = 'test';
$array[$i]['com'] = '';
break;
}
}
print_r($array);
If you are able to change the array on creation I would recommend shifting the id to the array's key identifier. Would make life a lot easier to just do:
$array[1]['name'] = 'test';
Otherwise use the for loop posted above and look it up. (Right awnser)
i have array with database, and have to select only this items what have "tid" = 1
array(3) {
[1]=>
array(4) {
["tid"]=> "1"
["title"]=> "Google"
["url"]=> "http://google.com/"
["description"]=> "A very efficient search engine."
}
[2]=>
array(4) {
["tid"]=> "2"
["title"]=> "Facebook"
["url"]=> "http://facebook.com/"
["description"]=> "Trade securities, currently supports nearly 1000 stocks and ETFs"
}
[3]=>
array(4) {
["tid"]=> "1"
["title"]=> "Yandex"
["url"]=> "http://yandex.ru/"
["description"]=> "Another efficient search engine popular in Russia"
}
}
how can i select only this items from array what have "tid" = 1?
<?php
$final_arr = array();
foreach($tid_arrs as $tid_arr){
if($tid_arr['tid'] == 1){
$final_arr[] = $tid_arr;
}
}
print_r($final_arr);
?>
$filteredArray = array();
for($i = 0, $end = count($array);$i < $end;i++)
{
if($array[$i]["tid"] === "1")
{
$filderedArray[] = $array[$i];
}
}
That way $filteredArray will contain solely the items with tid 1;
Try array_filter function: http://php.net/manual/en/function.array-filter.php this should help.
print_r(array_filter($array, "filter_function"));
function filter_function($element){
return (int)$element['tid'] === 1;
}
let's say you starting array is $arr.
$result = array();
foreach ($arr as $arrItem) {
if ((array_key_exists('tid', $arrItem)) && ($arrItem['tid'] == "1")){
$result[] = $arrItem;
}
}
$result should be what you are excepted.
I'm running two for each loops and pushing one of them into the other one. This works fine, except if my I have more than one match. In that case, I'm only getting the last one. Sorry about the title, not too sure how to call this question in one line.
foreach($items as &$item) {
foreach($fruits as &$fruit) {
$i = 0;
if($fruit['for']==$item['id']) {
$item["fruits"][$i] = $fruit;
$i++;
}
}
}
First array :
array(114) {
[0]=>
array(5) {
["id"]=>
string(2) "76"
...
}
...
}
Second array :
array(47) {
[0]=>
array(5) {
["id"]=>
string(1) "4"
["for"]=>
string(2) "76"
...
}
...
}
With multiple matches of the if($fruit['for']==$item['id']) logic, I'd like the following output.
array(114) {
[0]=>
array(6) {
["id"]=>
string(2) "76"
...
["fruits"]=>
array(2) {
[0]=>
array(5) {
["id"]=>
string(1) "4"
["for"]=>
string(2) "76"
...
}
[1]=>
array(5) {
["id"]=>
string(2) "33"
["for"]=>
string(2) "76"
...
}
}
}
}
What am I doing wrong?
take $i outside the loop, your match is always stored in $item["fruits"][0]
foreach($items as &$item) {
$i = 0;
foreach($fruits as &$fruit) {
if($fruit['for']==$item['id']) {
$item["fruits"][$i] = $fruit;
$i++;
}
}
}
You set $i to 0 for every array-element you check. This renders the $i++ useless and your first match gets overwritten. Try either this:
foreach($items as &$item) {
$i = 0;
foreach($fruits as &$fruit) {
if($fruit['for']==$item['id']) {
$item["fruits"][$i] = $fruit;
$i++;
}
}
}
or this: (depending on what exactly you will need)
$i = 0;
foreach($items as &$item) {
foreach($fruits as &$fruit) {
if($fruit['for']==$item['id']) {
$item["fruits"][$i] = $fruit;
$i++;
}
}
}
That way, each time you find a new match it gets a new key.
i am trying to sort out my array, just remove some duplicate elements etc... It all works great and looks like this when i output it
array(3) { ["addon_mat_3"]=> string(2) "15" ["addon_mat_7"]=> string(1) "7" ["addon_mat_15"]=> string(1) "9" }
The above is with this code
foreach ($new_shopping_list_array as $columnName => $columnData) {
if(is_numeric($columnName)){
unset($new_shopping_list_array[$columnName]);
}
if($columnName == 'addon_id'){
unset($new_shopping_list_array[$columnName]);
}
if($columnData == 0){
unset($new_shopping_list_array[$columnName]);
}
}
However, if i add the else as show below, which i need as it removes the first 10 characters from the array key, then i all of a sudden get a fourth element added to the array with key "0".
array(4) { [0]=> string(1) "9" [3]=> string(2) "15" [7]=> string(1) "7" [15]=> string(1) "9" }
This code
foreach ($new_shopping_list_array as $columnName => $columnData) {
if(is_numeric($columnName)){
unset($new_shopping_list_array[$columnName]);
}
if($columnName == 'addon_id'){
unset($new_shopping_list_array[$columnName]);
}
if($columnData == 0){
unset($new_shopping_list_array[$columnName]);
}else{
$new_columnName = substr($columnName, 10);
unset($new_shopping_list_array[$columnName]);
$new_shopping_list_array[$new_columnName] = $columnData;
}
}
Everything else is great, apart from that fourth element added, what am i doing wrong,
Thanks for any and all help
That code should work, but you could do the whole thing in a few less lines:
$flipped = array_flip($new_shopping_list_array);
foreach ($flipped as $value => &$key) {
if($key == "addon_id" || is_numeric($key) || $value == 0) {
unset($flipped[$value]);
} else {
$key = substr($key,10);
}
}
$new_shopping_list_array = array_flip($flipped);