php check if element exist through session array - php

How can I loop through set of session array and check if $_session['items'][1][p_alt-variation-1] and so on, are exist? the [p_alt-variation-{n}] elements are dynamic if certain item has these add-on variations, so it could be as much as more than 1
print_r($_session['items'])
Array
(
[0] => Array
(
[p_name] => Hovid PetSep
[p_code] => 336910
[p_coverImg] => 14-1460428610-ulNvG.jpg
[p_id] => 14
[p_price] => 24.50
[p_qty] => 2
)
[1] => Array
(
[p_name] => X-Dot Motorbike Helmet G88 + Bogo Visor (Tinted)
[p_code] => 2102649
[p_coverImg] => 12-1460446199-wI5qx.png
[p_id] => 12
[p_price] => 68.00
[p_alt-variation-1] => Red
[p_alt-variation-2] => L
[p_qty] => 1
)
)
I want to show for user if certain item has various variations in their cart if exist, how to look for element in array if contains string like [p_alt-variation-{n}] through?
I use foreach($_SESSION['items'] as $cart_item){ ... } to loop all cart items to show item's info.
Thanks for advice.

Not a regex guru, but you could just get the keys and check using preg_grep. If it has more than one key for that keyword, just count the results.
Here's the idea:
foreach($_SESSION['items'] as $cart_item) { // loop the items
$keys = array_keys($cart_item); // get the keys of the current batch
// make the expression
$matches = preg_grep('~^p_alt\-variation\-\d+~i', $keys); // simply just checking the key name with has a number in the end, adjust to your liking
if(count($matches) > 1) { // if it has more than one, or just change this to how many do you want
echo 'has more than one variation';
}
}
If you wanted to use some of that keys, just use the results that was found inside $matches:
if(count($matches) > 1) {
foreach($matches as $matched_key) {
echo $cart_item[$matched_key];
}
}

The session variables are just like any other array values; you can always use isset function. Please refer: http://php.net/manual/en/function.isset.php

Related

Can array_search return the key of the inner array of a multidimensional or nested array?

I am working on a shopping cart project and have a $_SESSION['productSummary'] array that looks like this.
[productSummary] => Array
(
[0] => Array
(
[name] => Individual Coins
[code] => 8774
[IDs] => Array
(
[0] => 8774
[1] => 8775
[2] => 8778
[3] => 8765
)
[pluID] => 6105
[qty] => 4
[finalPrice] => 0.0000
[listPrice] => 0.0000
[shipping] => 0.0000
)
[1] => Array
(
[name] => Business Package - 5,000
[code] => 8770
[IDs] => Array
(
[0] => 8770
)
[pluID] => 6087
[qty] => 1
[finalPrice] => 125.0000
[listPrice] => 125.0000
[shipping] => 0.0000
)
)
When the user wants to remove an item #8778 from the cart, I need to find the value of the index key for '8778' so I can remove that value from the array of IDs.
Here is the snip of code I have so far. I am getting good values for $matchingKey but $matchingKey2 is always empty.
// Find the key for the parent array
$matchingKey = array_search(8778, array_column($_SESSION["productSummary"], 'IDs'));
// Find the key for the element in the nested IDs array
$matchingKey2 = array_search(8778, array_column($_SESSION['productSummary'][$matchingKey]['IDs']));
// If it found a match, unset that element
if(!empty($matchingKey2)) {
unset($_SESSION["productSummary"][$matchingKey]['IDs'][$matchingKey2]);
}
// Reindex the array
$_SESSION["productSummary"][$matchingKey]['IDs'] = array_values($_SESSION["productSummary"][$matchingKey]['IDs']);
I was expecting
$matchingKey2 = array_search(8778, array_column($_SESSION['productSummary'][$matchingKey]['IDs']));
to return the value of 2 in this example, but instead if comes back as NULL
UPDATE: SOLVED
Based on the answers given, I updated my code to this and it seems to be working as expected now. (or at least until I break it again.) Thanks All
// $results is pulled from query of database based on a packageID - Short version is it puts all packaged inventory items in the cart and allows all to be taken out of the cart in as a group.
foreach ($results as $cartItem) {
// set cart time in the database back to NULL so it will appear in the store again
$query = "hidden";
dbWriteQuery($query);
// Remove item from SESSION['products']
$indexA = array_search($cartItem['inventoryID'], array_column($_SESSION["products"], 'code'));
if($indexA !== false) {
unset($_SESSION["products"][$indexA]);
}
// Reindex the array
$_SESSION["products"] = array_values($_SESSION["products"]);
// Remove item (or reduce qty) from SESSION['productSummary']
foreach ($_SESSION["productSummary"] as $key => $product) {
$indexB = array_search($cartItem['inventoryID'], $product['IDs']);
//Found a matching element
if ($indexB !== false) {
// if count of $product['IDs'] > 1, reduce the qty and remove the inventoryID from ID's
if(count($product['IDs'])>1) {
//reduct the qty
$_SESSION['productSummary'][$key]['qty'] = $_SESSION['productSummary'][$key]['qty'] - 1;
// remove the inventoryID from the IDs array
array_splice($_SESSION['productSummary'][$key]['IDs'], $indexB, 1);
// set the 'code' value equal to the next element in the IDs array
$_SESSION['productSummary'][$key]['code'] = $_SESSION['productSummary'][$key]['IDs'][0];
// else unset the whole element from ProductSummary
} else {
unset($_SESSION["productSummary"][$key]);
}
break;
}
}
// Reindex the array
$_SESSION["productSummary"] = array_values($_SESSION["productSummary"]);
}
You can't use array_search() to search nested arrays. Use an ordinary foreach loop.
Note also that you can't use !empty($matchingKey2) to tell if the item was found. If the item is the first element in the array, $matchingKey2 will be 0, which is considered empty. You have to use strict comparison with false.
foreach ($_SESSION["productSummary"] as &$product) {
$index = array_search(8778, $product['IDs']);
if ($index !== false) {
array_splice($product['IDs'], $index, 1);
break;
}
}

Find partial string inside array

I have this array from an AJAX request:
array (
[0] => 'lat,long#id_1'
[1] => 'lat,long#id_2'
[2] => 'lat,long#id_3'
)
The problem here is I'm not gonna have always a 'correct-ordered' array like that, so it may look like this one:
array (
[0] => 'lat,long#id_1'
[1] => 'lat,long#id_2'
[2] => 'lat,long#id_3'
[3] => 'lat,long#id_1'
[4] => 'lat,long#id_3'
[5] => 'lat,long#id_2'
)
I need to get the last array value of every id_X (currently only 3 ids):
array (
[3] => 'lat,long#id_1'
[4] => 'lat,long#id_3'
[5] => 'lat,long#id_2'
)
How can I find each last value of that array based on partial string (id_X)?
First do a reverse sort to ensure the latest values are parsed first. Then run them through a loop, matching the partial string to get the ID, adding the data to an array if the ID index doesn't exist yet. Last values will be added to your array, others will be neglected. Something like this:
rsort($ajaxy);
$lasts = [];
foreach($ajaxy as $str) {
$id = substr($str, strrpos($str, '#') + 1);
if (!isset($lasts[$id])) {
$lasts[$id] = $str;
}
}
var_dump($lasts);
If you have a huge array, and you know the amount of IDs you will be getting, you can add in a check to terminate the loop when all required IDs have been added in to avoid redundant processing.
Otherwise, don't bother with the reverse sort, and simply keep overwriting previous values 'til the end, but I find this a cleaner approach. ^_^

Confused with session and array

I have a session variable named $_SESSION['items'] that is an array. It stores items in arrays, inside its array. For example:
Array ( [0] => Array ( [0] => 2 [1] => 1 ) )
This show that there is 1 of product 2 in the items array.
Array ( [0] => Array ( [0] => 2 [1] => 1 ) [1] => Array ( [0] => 4 [1] => 1 ) )
This shows that there is 1 of item 2, and 1 of item 4 in the items array..
How so I check if a specific variable is in the items array? For example, i need to know if item 4 or item 1 is in this array so I can show the user a different page depending on if they have this item in their array or not. I get so confused with arrays that I always call undefined offsets and the like.
Figured it out. had a brain fart. thanks
foreach($_SESSION['items'] as $key => $item) {
if($item[0] == $item_id) {
echo "ITEM IS IN HERE";
}
}
//Try using array search good way
Try following this will help you to get the position where found and return nothing if not found
You dont need to loop through.
// this will search $item_id in $_SESSION['items']
$key = array_search($item_id, array_column($_SESSION['items'], 0)); //here 0 is position, see array_search
print_r($key);
if($key){
//yes found at key so that you can easily get that item again without looping
}

Get key values from multidimensional array

I have a page that searches a database and generates the following array. I'd like to be able to loop through the array and pick out the value next assigned to the key "contact_id" and do something with it, but I have no idea how to get down to that level of the array.
The array is dynamically generated, so depending on what I search for the index numbers under "values" will change accordingly.
I'm thinking I have to do a foreach starting under values, but I don't know how to start a foreach at a sublevel of an array.
Array (
[is_error] => 0
[version] => 3
[count] => 2
[values] => Array (
[556053] => Array (
[contact_id] => 556053
[contact_type] => Individual
[first_name] => Brian
[last_name] => YYY
[contact_is_deleted] => 0
)
[596945] => Array (
[contact_id] => 596945
[contact_type] => Individual
[first_name] => Brian
[last_name] => XXX
[contact_is_deleted] => 0
)
)
)
I've looked at the following post, but it seems to only address the situation where the array indices are sequential.
Multidimensional array - how to get specific values from sub-array
Any ideas?
Brian
You are correct in your assumption. You could do something like this:
foreach($array['values'] as $key => $values) {
print $values['contact_id'];
}
That should demonstrate starting at a sub level. I would also add in your checks to see if its empty and if its an array... etc.
Another hint regarding syntax - if the array in your original example is called $a, then the values you want are here:
$a['values'][556053]['contact_id']
and here:
$a['values'][596945]['contact_id']
So if there's no additional structure in your array, then this loop is probably what you want:
foreach ($a['values'] as $toplevel_id => $record_data) {
print "for toplevel_id=[$toplevel_id], contact_id=[" . $record_data['contact_id'] . "]\n";
}
foreach($array['values'] as $sub_arr){
echo $sub_arr['contact_id'];
}

PHP - Check that value doesn't appear twice in array

I have a array inside my PHP app that looks like this:
Array
(
[0] => Array
(
[name] => Name1
[language] => 1
)
[1] => Array
(
[name] => Name2
[language] => 1
)
)
How can I check that "language" with value 1 doesnt appear twice, as effectively as possible?
$dupe = 0;
foreach($yourarray as $key => $val) {
if(array_key_exists($seen, $val['language'])) {
// a duplicate exists!
$dupe = 1;
// could do other stuff here too if you want,
// like if you want to know the $key with the dupe
// if all you care about is whether or not any dupes
// exist, you could use a "break;" here to early-exit
// for efficiency. To find all dupes, don't use break.
}
$seen[$val['language']] = 1;
}
// If $dupe still = 0 here, then no duplicates exist.
Tried the PHP function array_unique?
(Read the comments/user contributed notes below, especially the one by regeda at inbox dot ru, who made a recursive function for multi-dimensional arrays)

Categories