filter multidimensional array by value - php

I have the following array:
$entrate=Array
(
0 => Array(
'id' => 1,
'nome' => 'Stipendio',
'datamov' => '2023-04-15',
'mese' => 4,
'anno' => 2023,
'total_mov' => 3000.00
),
1 => Array(
'id' => 1,
'nome' => 'Stipendio',
'datamov' => '2023-03-15',
'mese' => 3,
'anno' => 2023,
'total_mov' => 3000.00
),
2 => Array(
'id' => 1,
'nome' => 'Stipendio',
'datamov' => '2023-02-15',
'mese' => 2,
'anno' => 2023,
'total_mov' => 3000.00
),
3 => Array(
'id' => 1,
'nome' => 'Stipendio',
'datamov' => '2023-01-15',
'mese' => 1,
'anno' => 2023,
'total_mov' => 3000.00
),
4 => Array(
'id' => 4,
'nome' => 'Interessi Attivi',
'datamov' => '',
'mese' => '',
'anno' => '',
'total_mov' => 'VUOTO'
)
);
Starting from this I want to be able to select a specific 'nome' and filter the array to return just the items of this array that match that 'nome'.
So for example if I want to filter by 'Stipendio' I'll get the first three elements only.
If I filter by 'Interessi Attivi' just the fourth. If I filter by 'some other key' I'll get an empty array.
I was trying to use
$tipo_mov='Stipendio';
$entrata = array_filter($entrate, function ($value) use ($tipo_mov) {
return ($entrate[$key]['nome'] == $tipo_mov);
});
but I cannot shape it so that it'll give me back the expected filtering (this code is not running obviously and throwing a bunch of errors).
What am I missing?

$value in array_filter() are the inner arrays of $entrate, so you want to search for a match on $value['nome']:
https://paiza.io/projects/BmEdekWY8elJ90rIPjTGGQ
$tipo_mov='Stipendio';
$entrata = array_filter($entrate, function ($value) use ($tipo_mov)
{
return $value['nome'] == $tipo_mov;
});
print_r($entrata);

Related

array_multisort() with a variable/dynamic number of parameters does not affect the original array [duplicate]

This question already has answers here:
Sort array using array_multisort() with dynamic number of arguments/parameters/rules/data
(5 answers)
Closed last month.
I'm using array_multisort (PHP 7.4) to apply a mutli-dimensional sort. I think I'm using it correctly, but the result is not what I would expect. No matter what direction I set, it only sorts ascending (even if I set both to SORT_DESC). I tried different sort flags (e.g. SORT_STRING, SORT_NATURAL), but this did not make a difference.
$definitions = [
[
'name' => 'Bart',
'age' => 12,
'location' => 'Brazil',
],
[
'name' => 'Daniel',
'age' => 51,
'location' => 'Brazil',
],
[
'name' => 'Adam',
'age' => 33,
'location' => 'France',
],
[
'name' => 'Adam',
'age' => 44,
'location' => 'France',
],
[
'name' => 'Adam',
'age' => 5,
'location' => 'France',
],
[
'name' => 'Zed',
'age' => 21,
'location' => 'GB',
],
];
$sorting = [
[
'field' => 'name',
'direction' => SORT_ASC,
],
[
'field' => 'age',
'direction' => SORT_DESC,
]
];
$sort_args = [];
foreach ($sorting as $sort) {
$sort_args[] = array_column($definitions, $sort['field']);
$sort_args[] = $sort['direction'];
$sort_args[] = SORT_REGULAR;
}
array_multisort($definitions, ...$sort_args);
The result:
array (
0 =>
array (
'name' => 'Adam',
'age' => 5,
'location' => 'France',
),
1 =>
array (
'name' => 'Adam',
'age' => 33,
'location' => 'France',
),
2 =>
array (
'name' => 'Adam',
'age' => 44,
'location' => 'France',
),
3 =>
array (
'name' => 'Bart',
'age' => 12,
'location' => 'Brazil',
),
4 =>
array (
'name' => 'Daniel',
'age' => 51,
'location' => 'Brazil',
),
5 =>
array (
'name' => 'Zed',
'age' => 21,
'location' => 'GB',
),
)
What I expected:
array (
0 =>
array (
'name' => 'Adam',
'age' => 44,
'location' => 'France',
),
1 =>
array (
'name' => 'Adam',
'age' => 33,
'location' => 'France',
),
2 =>
array (
'name' => 'Adam',
'age' => 5,
'location' => 'France',
),
3 =>
array (
'name' => 'Bart',
'age' => 12,
'location' => 'Brazil',
),
4 =>
array (
'name' => 'Daniel',
'age' => 51,
'location' => 'Brazil',
),
5 =>
array (
'name' => 'Zed',
'age' => 21,
'location' => 'GB',
),
)
Am I missing something or is this busted?
You have the arguments in the wrong order. The array you wish to sort should be the last item for this type of sorting.
Example #3: https://www.php.net/manual/en/function.array-multisort.php#example-5040
You may have done this so that you can use the spread operator (which is fine). If you want to continue using the spread operator you would adjust your code as so:
$sort_args[] = &$definitions; // add this line
array_multisort(...$sort_args); // remove `$definitions` from this line
Note that we are passing $definitions as reference otherwise when we push it to $sort_args, we would be creating a copy (due to the nature of PHP).
Without passing by reference, that original array won't be sorted, only the copy we created.

Is there a chance that array_slice is bugged - returning wrong

Is there a chance to array_slice is bugged (using PHP 8.0.12)
I were looking for best way to get few elements(limited) of array with possible offset so tried to array_slice but its keep return me wrong index then i expect
I have array with objects from database and they looks like(ill write only id)
$questions simplified to only id
$limit = 1;
$questions = array(
array(
'id' => 2,
'stage' => 1,
'question_order' => 0,
'many_answers' => 0,
'points' => 5.5,
'spread_points_in_time' => 0,
'question' => "Czy Johnny Deep grał Jack'a Sparow'a?",
'time' => "00:00:10"
),
array(
'id' => 3,
'stage' => 1,
'question_order' => 0,
'many_answers' => 0,
'points' => 4.5,
'spread_points_in_time' =>0,
'question' => "Producent laptopa Darka",
'time' => "00:00:00"
),
array(
'id' => 1,
'stage' => 1,
'question_order' => 0,
'many_answers' => 0,
'points' => 10,
'spread_points_in_time' => 0,
'question' => "Która klawiatura jest mechniczna",
'time' => "00:00:10"
),
array(
'id' => 8,
'stage' => 2,
'question_order' => 0,
'many_answers' => 0,
'points' => 30,
'spread_points_in_time' => 1,
'question' => "2*2",
'time' => "00:00:30"
),
array(
'id' => 4,
'stage' => 2,
'question_order' => 0,
'many_answers' => 0,
'points' => 30,
'spread_points_in_time' => 0,
'question' => "Który język programowania ma dostęp do komórek pamięci komputera?",
'time' => "00:00:30"
),
array(
'id' => 7,
'stage' => 2,
'question_order' => 0,
'many_answers' => 0,
'points' => 30,
'spread_points_in_time' => 0,
'question' => "2+2",
'time' => "00:00:30"
),
array(
'id' => 10,
'stage' => 3,
'question_order' => 1,
'many_answers' => 1,
'points' => 5,
'spread_points_in_time' => 0,
'question' => "Jaki jest symbol chemiczny srebra?",
'time' => "00:00:00"
),
array(
'id' => 11,
'stage' => 3,
'question_order' => 0,
'many_answers' => 1,
'points' => 5,
'spread_points_in_time' => 0,
'question' => "Jaka jest żywotność ważki?",
'time' => "00:00:00"
),
array(
'id' => 9,
'stage' => 3,
'question_order' => 0,
'many_answers' => 0,
'points' => 5,
'spread_points_in_time' => 0,
'question' => "W którym roku Titanic zatonął na Oceanie Atlantyckim 15 kwietnia podczas dziewiczej podróży z Southampton?",
'time' => "00:00:00"
)
);
echo json_encode(
array(
'all' => $questions,
'limit' => $limit,
'sliced' => array_slice($questions, 0, $limit),
)
);
so when i try array_splice(array, 0, 1) i would expect 1 so id should be 2 but instead i get object which have id 1
i also tried with flag to keep indexed but then i end up same but with true index of object with id 1 (then key is 2)
If i put limit as 2 then i get object with id 1 and also object with id 2 (flag to keep indexed also return me properly to objects 2 and 0)
Also tried to remove id from every object by
foreach($questions as $key => $question)
{
unset($questions[$key]['id'];
}
But this didnt changed anything
$questions source https://pastebin.com/wDfJdm9Z
After plenty of combinations i figured it out
I were sorting this array before everything with forcing keys
So in sorting it looked like
foreach($toSort as $key => $item)
{
foreach($ids as $idKey => $id)
{
if($item['id'] == $id)
{
$sorted[$idKey] = $item;
break;
}
}
}
So for example array could end up with wrong order of keys like:
array(
[1] => item2,
[0] => item1,
[2] => item3
);
I were expecting array gona shove key 0 to be index 0 but don't looks like
Setting something to exact key isn't same as set something to set at exact index
SOLUTION WAS add ksort($sorted) before return $sorted

Issue with Unset (PHP)

I am trying to unset an item from session array, it unset once then brings back again.
for exg :-
if i click to remove itemId = 5, it removes from session array,
then i click to remove itemId = 6, then i see the old itemId = 5 is back in array again.
/*** delete item from cart ***/
public function deleteCartItem($id, $customerId, $cartId, $wishlistFlag=false) // Param: ProductID, CustomerID, CartID, WishlistFlag
{
$conn = $_SESSION['conn'];
$itemId = false;
$chk = array();
$sql = "DELETE FROM cart_items WHERE product_id=? AND cart_id=?";
$stmt = mysqli_prepare($conn, $sql);//$result = $conn->query($sql);
$stmt->bind_param('ii', $item['id'],$cartId);
$stmt->execute();
$itemId = $i;
echo $itemId;
$chk[] = $_SESSION['cart'];
echo'</br>';
print_r($chk);
}
}
if (isset($_SESSION['cart'][$itemId])){
unset($_SESSION['cart'][$itemId]);
}
}
<?php
$_SESSION['cart'] = array (
0 =>
array (
'id' => 6154353459,
'name' => 'pro one Night Out Mesh Tee',
'display_brand' => 'Widow',
'qty' => 1,
'price' => '28.0000',
'special_price' => 0,
'rule_price' => '',
'attributes' =>
array (
0 => 'BLACK',
1 => 'XX-Large',
),
'option80' => 18,
'option125' => 3457,
'child_product_id' => 61535897,
'giftcard' => '',
'whole_preorder' => 0,
'preorder_shipping_date' => NULL,
'available_qty' => 5,
'isRefundable' => true,
'max_sale_qty' => false,
'isFree' => 0,
'segment' =>
array (
'magento_product_id' => '65315459',
'product_id' => 'P19335935',
'quantity' => 1,
'name' => 'pro one Night Out Mesh Tee',
'brand' => 'Widow',
'price' => 28.0,
'special_price' => NULL,
'regular_price' => 28.0,
'size_type' => 'Regular',
'manufacturer' => 'Widow',
'trend' => 'WID goodie Hour 2020',
'microcategory' => 'Mesh Shirt',
'doll_category' => NULL,
'stock_quantity' => 10,
'sku' => 'S493660',
'child_stock_quantity' => 1,
'size' => 'XX-Large',
'swatch' => 'BLACK',
),
),
5 =>
array (
'id' => 615345465,
'name' => 'pro one Night Out Mesh Leggings',
'display_brand' => 'Widow',
'qty' => 1,
'price' => '30.0000',
'special_price' => 0,
'rule_price' => '',
'attributes' =>
array (
0 => 'BLACK',
1 => 'Medium',
),
'option80' => 18,
'option125' => 3454,
'child_product_id' => 6315890,
'giftcard' => '',
'whole_preorder' => '',
'preorder_shipping_date' => NULL,
'available_qty' => 37,
'isRefundable' => true,
'max_sale_qty' => false,
'isFree' => 0,
'segment' =>
array (
'magento_product_id' => '64334515465',
'product_id' => 'P193936',
'quantity' => 1,
'name' => 'pro one Night Out Mesh Leggings',
'brand' => 'Widow',
'price' => 30.0,
'special_price' => NULL,
'regular_price' => 30.0,
'size_type' => 'Regular',
'manufacturer' => 'Widow',
'trend' => 'WID goodie Hour 2020',
'microcategory' => 'Printed Leggings',
'doll_category' => NULL,
'stock_quantity' => 10,
'sku' => 'S493664',
'child_stock_quantity' => 10,
'size' => 'Medium',
'swatch' => 'BLACK',
),
),
2 =>
array (
'id' => 615445348,
'name' => 'pro two My Lashes Sunglasses',
'display_brand' => '',
'qty' => 1,
'price' => '15.0000',
'special_price' => 0,
'rule_price' => '',
'attributes' =>
array (
0 => 'BLACK',
1 => 'ONE SIZE',
),
'option80' => 18,
'option125' => 6212,
'child_product_id' => 6154345358,
'giftcard' => '',
'whole_preorder' => '',
'preorder_shipping_date' => NULL,
'available_qty' => 295,
'isRefundable' => true,
'max_sale_qty' => false,
'isFree' => 0,
'segment' =>
array (
'magento_product_id' => '6153453448',
'product_id' => 'P19645642180',
'quantity' => 1,
'name' => 'pro two My Lashes Sunglasses',
'brand' => '',
'price' => 15.0,
'special_price' => NULL,
'regular_price' => 15.0,
'size_type' => 'Regular',
'manufacturer' => 'CIEL',
'trend' => 'WID goodie Hour 2020',
'microcategory' => 'Cat Eye Sunglasses',
'category' => 'Accessories,Sunglasses,Cat Eye Sunglasses',
'special_category' => 'What\'s New,Char Test Category,Widow',
'doll_category' => NULL,
'stock_quantity' => 10,
'sku' => 'S486477',
'child_stock_quantity' => 10,
'size' => 'ONE SIZE',
'swatch' => 'BLACK',
),
),
3 =>
array (
'id' => 61465645461,
'name' => 'pro one Night Out goodie Dress',
'display_brand' => 'Widow',
'qty' => 1,
'price' => '45.0000',
'special_price' => 0,
'rule_price' => '',
'attributes' =>
array (
0 => 'BLACK',
1 => 'X-Large',
),
'option80' => 18,
'option125' => 3456,
'giftcard' => '',
'whole_preorder' => '',
'preorder_shipping_date' => NULL,
'available_qty' => 12,
'isRefundable' => true,
'max_sale_qty' => false,
'isFree' => 0,
'segment' =>
array (
'magento_product_id' => '616465461',
'product_id' => 'P1935446934',
'quantity' => 1,
'name' => 'pro one Night Out goodie Dress',
'brand' => 'Widow',
'price' => 45.0,
'special_price' => NULL,
'regular_price' => 45.0,
'size_type' => 'Regular',
'manufacturer' => 'Widow',
'trend' => 'WID goodie Hour 2020',
'microcategory' => 'goodie Dresses',
'category' => 'Clothing,Dresses,Mini,goodie Dresses',
'special_category' => 'Brandsgoodie,Char Test Category,Widow,Widow',
'doll_category' => NULL,
'stock_quantity' => 10,
'sku' => 'S493652',
'child_stock_quantity' => 10,
'size' => 'X-Large',
'swatch' => 'BLACK',
),
),
4 =>
array (
'id' => 6154566225,
'name' => 'Feelings Maxi Dress',
'display_brand' => 'Widow',
'qty' => 1,
'price' => '58.0000',
'special_price' => 0,
'rule_price' => '',
'attributes' =>
array (
0 => 'BLACK',
1 => 'Large',
),
'option80' => 18,
'option125' => 3455,
'child_product_id' => 61456455677,
'giftcard' => '',
'whole_preorder' => '',
'preorder_shipping_date' => NULL,
'available_qty' => 30,
'isRefundable' => true,
'max_sale_qty' => false,
'isFree' => 0,
'segment' =>
array (
'magento_product_id' => '614565225',
'product_id' => 'P1945652050',
'quantity' => 1,
'name' => 'Phantom Feelings Maxi Dress',
'brand' => 'Widow',
'price' => 58.0,
'special_price' => NULL,
'regular_price' => 58.0,
'size_type' => 'Regular',
'manufacturer' => 'Widow',
'trend' => 'WID goodie Hour 2020',
'microcategory' => 'Maxi Dresses',
'category' => 'Dresses,Midi & Maxi,Maxi Dresses',
'special_category' => 'Brandsgoodie,Char Test Category,Widow,Widow',
'doll_category' => NULL,
'stock_quantity' => 10,
'sku' => 'S485794',
'child_stock_quantity' => 10,
'size' => 'Large',
'swatch' => 'BLACK',
),
)
);
$itemId = 5; // comes dybamically;
if ( isset($_SESSION['cart'][$itemId])) {
unset($_SESSION['cart'][$itemId]);
}
?>
I am not getting it,
Any thoughts ?
You can also take a look at the sandbox- http://sandbox.onlinephpfunctions.com/code/6bab394d1da39a301ce82b974022da7b7efaface
Please refer to the whole code here - PHP SESSION UPDATE ISSUE
Thankyou
You're proably re-reading session-data so that deletion you're making is overridden.
<?php
$cart = $_SESSION['cart'];
unset($cart[5]);
echo 'deletion confirmed';
//later in execution..
//accidental re-read of cart from session-variable.
//BAD CODE STARTS HERE
$cart = $_SESSION['cart']; //error since you're re-reading cart from session.
//BAD CODE END
//calc totals in basket or something..
$totals = 0;
foreach($cart as $item) {
$totals = $totals + $item['qty'] * $item['price'];
}
//somewhere in the script, the session variable is updated.
$_SESSION['cart'] = $cart;
GOOD TO KNOW
PHP passes most variables by value as default, meaning that
$cart = $_SESSION['cart'];
copies the content of $_SESSION['cart'] into $cart.
Any change made to $cart will not automatically be updated in $_SESSION['cart'].
If you don't want a copy but a reference, you may use:
$cart = &$_SESSION['cart'];
and you will not need to save $cart into $_SESSION.
(Just make sure $_SESSION['cart'] is initialized when making the reference)
** AND **
Session variables tend to grow to a mess.. Use getters and setters in your application.
The best approach is to after unset get the updated array from session and declare it again
$cart_array = array (
0 =>
array (
'id' => 6154353459,
'name' => 'pro one Night Out Mesh Tee',
'display_brand' => 'Widow',
'qty' => 1,
'price' => '28.0000',
'special_price' => 0,
'rule_price' => '',
'attributes' =>
array (
0 => 'BLACK',
1 => 'XX-Large',
),
'option80' => 18,
'option125' => 3457,
'child_product_id' => 61535897,
'giftcard' => '',
'whole_preorder' => 0,
'preorder_shipping_date' => NULL,
'available_qty' => 5,
'isRefundable' => true,
'max_sale_qty' => false,
'isFree' => 0,
'segment' =>
array (
'magento_product_id' => '65315459',
'product_id' => 'P19335935',
'quantity' => 1,
'name' => 'pro one Night Out Mesh Tee',
'brand' => 'Widow',
'price' => 28.0,
'special_price' => NULL,
'regular_price' => 28.0,
'size_type' => 'Regular',
'manufacturer' => 'Widow',
'trend' => 'WID goodie Hour 2020',
'microcategory' => 'Mesh Shirt',
'doll_category' => NULL,
'stock_quantity' => 10,
'sku' => 'S493660',
'child_stock_quantity' => 1,
'size' => 'XX-Large',
'swatch' => 'BLACK',
),
),
5 =>
array (
'id' => 615345465,
'name' => 'pro one Night Out Mesh Leggings',
'display_brand' => 'Widow',
'qty' => 1,
'price' => '30.0000',
'special_price' => 0,
'rule_price' => '',
'attributes' =>
array (
0 => 'BLACK',
1 => 'Medium',
),
'option80' => 18,
'option125' => 3454,
'child_product_id' => 6315890,
'giftcard' => '',
'whole_preorder' => '',
'preorder_shipping_date' => NULL,
'available_qty' => 37,
'isRefundable' => true,
'max_sale_qty' => false,
'isFree' => 0,
'segment' =>
array (
'magento_product_id' => '64334515465',
'product_id' => 'P193936',
'quantity' => 1,
'name' => 'pro one Night Out Mesh Leggings',
'brand' => 'Widow',
'price' => 30.0,
'special_price' => NULL,
'regular_price' => 30.0,
'size_type' => 'Regular',
'manufacturer' => 'Widow',
'trend' => 'WID goodie Hour 2020',
'microcategory' => 'Printed Leggings',
'doll_category' => NULL,
'stock_quantity' => 10,
'sku' => 'S493664',
'child_stock_quantity' => 10,
'size' => 'Medium',
'swatch' => 'BLACK',
),
),
2 =>
array (
'id' => 615445348,
'name' => 'pro two My Lashes Sunglasses',
'display_brand' => '',
'qty' => 1,
'price' => '15.0000',
'special_price' => 0,
'rule_price' => '',
'attributes' =>
array (
0 => 'BLACK',
1 => 'ONE SIZE',
),
'option80' => 18,
'option125' => 6212,
'child_product_id' => 6154345358,
'giftcard' => '',
'whole_preorder' => '',
'preorder_shipping_date' => NULL,
'available_qty' => 295,
'isRefundable' => true,
'max_sale_qty' => false,
'isFree' => 0,
'segment' =>
array (
'magento_product_id' => '6153453448',
'product_id' => 'P19645642180',
'quantity' => 1,
'name' => 'pro two My Lashes Sunglasses',
'brand' => '',
'price' => 15.0,
'special_price' => NULL,
'regular_price' => 15.0,
'size_type' => 'Regular',
'manufacturer' => 'CIEL',
'trend' => 'WID goodie Hour 2020',
'microcategory' => 'Cat Eye Sunglasses',
'category' => 'Accessories,Sunglasses,Cat Eye Sunglasses',
'special_category' => 'What\'s New,Char Test Category,Widow',
'doll_category' => NULL,
'stock_quantity' => 10,
'sku' => 'S486477',
'child_stock_quantity' => 10,
'size' => 'ONE SIZE',
'swatch' => 'BLACK',
),
),
3 =>
array (
'id' => 61465645461,
'name' => 'pro one Night Out goodie Dress',
'display_brand' => 'Widow',
'qty' => 1,
'price' => '45.0000',
'special_price' => 0,
'rule_price' => '',
'attributes' =>
array (
0 => 'BLACK',
1 => 'X-Large',
),
'option80' => 18,
'option125' => 3456,
'giftcard' => '',
'whole_preorder' => '',
'preorder_shipping_date' => NULL,
'available_qty' => 12,
'isRefundable' => true,
'max_sale_qty' => false,
'isFree' => 0,
'segment' =>
array (
'magento_product_id' => '616465461',
'product_id' => 'P1935446934',
'quantity' => 1,
'name' => 'pro one Night Out goodie Dress',
'brand' => 'Widow',
'price' => 45.0,
'special_price' => NULL,
'regular_price' => 45.0,
'size_type' => 'Regular',
'manufacturer' => 'Widow',
'trend' => 'WID goodie Hour 2020',
'microcategory' => 'goodie Dresses',
'category' => 'Clothing,Dresses,Mini,goodie Dresses',
'special_category' => 'Brandsgoodie,Char Test Category,Widow,Widow',
'doll_category' => NULL,
'stock_quantity' => 10,
'sku' => 'S493652',
'child_stock_quantity' => 10,
'size' => 'X-Large',
'swatch' => 'BLACK',
),
),
4 =>
array (
'id' => 6154566225,
'name' => 'Feelings Maxi Dress',
'display_brand' => 'Widow',
'qty' => 1,
'price' => '58.0000',
'special_price' => 0,
'rule_price' => '',
'attributes' =>
array (
0 => 'BLACK',
1 => 'Large',
),
'option80' => 18,
'option125' => 3455,
'child_product_id' => 61456455677,
'giftcard' => '',
'whole_preorder' => '',
'preorder_shipping_date' => NULL,
'available_qty' => 30,
'isRefundable' => true,
'max_sale_qty' => false,
'isFree' => 0,
'segment' =>
array (
'magento_product_id' => '614565225',
'product_id' => 'P1945652050',
'quantity' => 1,
'name' => 'Phantom Feelings Maxi Dress',
'brand' => 'Widow',
'price' => 58.0,
'special_price' => NULL,
'regular_price' => 58.0,
'size_type' => 'Regular',
'manufacturer' => 'Widow',
'trend' => 'WID goodie Hour 2020',
'microcategory' => 'Maxi Dresses',
'category' => 'Dresses,Midi & Maxi,Maxi Dresses',
'special_category' => 'Brandsgoodie,Char Test Category,Widow,Widow',
'doll_category' => NULL,
'stock_quantity' => 10,
'sku' => 'S485794',
'child_stock_quantity' => 10,
'size' => 'Large',
'swatch' => 'BLACK',
),
)
);
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = $cart_array;
} else {
$_SESSION['cart'] = (array) $_SESSION['cart'];
}
$itemId = 3;
if (isset($_SESSION['cart'][$itemId])) {
unset($_SESSION['cart'][$itemId]);
}
print_r($_SESSION['cart']);
Now it will be not back the remove item again, unless if you destroy the session
Why is there $item['id'] used in $stmt->bind_param( (instead of $id?). $item is not a parameter of the function.
Similarly, where does the variable $i come from in $itemId = $i;?
I have written a simplified version of your problem and it works as expected. It uses a form and buttons to give the array indices to the PHP script. If you have a different setup (like using Ajax) you need to clarify that.
session_start();
if (!isset($_SESSION['cart']) || sizeof($_SESSION['cart']) === 0)
{
echo('Resetting cart.' . PHP_EOL);
$_SESSION['cart'] = [0 =>'zero', 1 =>'one', 2 =>'two', 3 =>'three', 4 =>'four'];
}
echo('<pre>before ' . print_r($_SESSION['cart'], TRUE) . '</pre>');
$itemId = isset($_GET['itemid']) ? $_GET['itemid'] : FALSE;
if ($itemId !== FALSE)
{
if (isset($_SESSION['cart'][$itemId]))
{
echo('Unsetting »' . $itemId . '«.' . PHP_EOL);
unset($_SESSION['cart'][$itemId]);
}
else
echo('»' . $itemId . '« not in cart.' . PHP_EOL);
}
else
echo('No item ID given.' . PHP_EOL);
echo('<pre>after ' . print_r($_SESSION['cart'], TRUE) . '</pre>');
echo('<form method="get" action="' . $_SERVER['PHP_SELF'] . '">' . PHP_EOL);
foreach ($_SESSION['cart'] as $key=>$value)
echo('<button name="itemid" value="' . $key . '">' . $value . '</button>' . PHP_EOL);
echo('</form>' . PHP_EOL);
The manual has made it clear
If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
To unset() a global variable inside of a function, then use the $GLOBALS array to do so:
<?php
function foo()
{
unset($GLOBALS['bar']);
}
$bar = "something";
foo();
?>
$stmt->bind_param('ii', $item['id'],$cartId);
$stmt->execute();
where is $item['id'] from?
Try using different variable names on your bind_param and declare their value before query execute() method.

Return partial matches from multidimensional array search in PHP

I'm very new to PHP so any help here is greatly appreciated. I have an array that I need to search and return partial and exact matches. Here's the array and where I've started code-wise:
$employeeList = array(
array(
'action' => false,
'title' => '2015 Performance Appraisal - Basille, Victor P.',
'type' => 'Employee Assessment',
'status' => 'Evaluate',
'date' => 'Dec 12, 2015',
'actions' => array('Start','Delete','View Progress','Manage Rater and Peers','Print'),
'employeeName' => 'Basille, Victor P.',
'employeeProgress' => 0,
'employeeStatus' => 'Not Yet Started',
'raterName' => 'Crane, Davy L.',
'raterProgress' => 0,
'raterStatus' => 'Not Yet Started',
'peers' => 3,
'peersComplete' => 0
),
array(
'action' => true,
'title' => '2015 Performance Appraisal - Bradford, Julie D.',
'type' => 'Employee Assessment',
'status' => 'Evaluate',
'date' => 'Dec 12, 2015',
'actions' => array('Resume','Reset','View Progress','Delete','Manage Rater and Peers','Print'),
'employeeName' => 'Bradford, Julie D.',
'employeeProgress' => 10,
'employeeStatus' => 'In Progress',
'raterName' => 'Crane, Davy L.',
'raterProgress' => 60,
'raterStatus' => 'In Progress',
'peers' => 3,
'peersComplete' => 1
),
array(
'action' => false,
'title' => '2015 Performance Appraisal - Fiedler, Joanne M.',
'type' => 'Employee Assessment',
'status' => 'Review',
'date' => 'Dec 12, 2015',
'actions' => array('View','Reset','Revert','View Progress','Print'),
'employeeName' => 'Fiedler, Joanne M.',
'employeeProgress' => 100,
'employeeStatus' => 'Submitted',
'raterName' => 'Fay, Lester P.',
'raterProgress' => 100,
'raterStatus' => 'Submitted',
'peers' => 3,
'peersComplete' => 3
)
);
$search_term = 'Victor';
$key = array_search($search_term, array_column($employeeList, 'title'));
This works great, except it only works for exact matches of the 'title'. How can I make this return partial matches as well?
Thanks.
what you need is preg_grep() which searchs the array for patern matching elements and returns them in an array.
http://php.net/manual/en/function.preg-grep.php
$result_array = preg_grep("/{$keyword}/i",$employeeList)

How to get all the specific key value from multidimensional array in php?

How can I get the all the 'name' and 'city' value back in an array from the following multidimensional array?
$myarray=Array(Array('name' => 'A','id' => '1', 'phone' => '416-23-55',
Base => Array ('city' => 'toronto'),'EBase' => Array('city' => 'North York'),
'Qty' => '1'), (Array('name' =>'B','id' => '1','phone' => '416-53-66','Base' =>
Array ('city' => 'qing'), 'EBase' => Array('city' => 'chong'),'Qty' => '2')));
I expect the returned value be
$namearray=Array('A','B');
$basecityarray=Array('toronto','qing');
$Ebasecityarray=Array('North York','chong');
Thank you!
You can definitely try something like this:
$shop = array( array( 'Title' => "rose",
'Price' => 1.25,
'Number' => 15
),
array( 'Title' => "daisy",
'Price' => 0.75,
'Number' => 25,
),
array( 'Title' => "orchid",
'Price' => 1.15,
'Number' => 7
)
);
You can access the first row as
echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2]."<br />";
or $shop[0]->Title will return to you rose.

Categories