Issue with Unset (PHP) - 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.

Related

Filter and re-format a given multi-dimensional array (php)

I have been given a dataset by my tutor and asked to carry out the following:
// make a function
// get skus of which the figure of the average monthly sales unit is equal or greater than 350
// array in the following format:
[
'id' => 11102,
'sku' => 'TEST_3',
'alternates' => [
'asin' => [
'code' => '50',
'value' => 'JL1235',
],
'barcode' => [
'code' => '10',
'value' => 'JS160694',
],
],
'commodityCode' => '9989898889',
'price' => [
'value' => 145.99,
],
'instructions' => [
'picking' => [
'code' => 'PICK',
'value' => 'I\'VE JUST HAD AN UNHAPPY LOVE AFFAIR, SO I DON\'T SEE WHY ANYBODY ELSE SHOULD HAVE A GOOD TIME.',
],
],
'quantity' => [
'inner' => 100,
'masterCarton' => 200,
'pallet' => 300,
],
'averageMonthlyUnitSales' => 100,
'created_at' => '2022-03-13 04:14:12'
],
Example dataset is here:
$data = [
[
'id' => '9947',
'sku' => 'test_1',
'asin_code' => '50',
'asin_value' => '',
'barcode' => '10',
'barcode_value' => 'js160694',
'commodityCode' => '9989898889',
'price' => '120.50',
'picking_instruction_code' => 'PICK',
'picking_instruction_value' => '',
'qty_inner' => '120',
'qty_masterCarton' => '200',
'qty_pallet' => '1200',
'averageMonthlyUnitSales' => '750',
'created_at' => '2019-02-23T01:54:14.957299+00:00'
],
[
'id' => '10921',
'sku' => 'test_2',
'asin_code' => '50',
'asin_value' => 'bx12345',
'barcode' => '10',
'barcode_value' => 'jb170931',
'commodityCode' => '9989898889',
'price' => '20.59',
'picking_instruction_code' => 'PICK',
'picking_instruction_value' => 'It\'s only half completed, I\'m afraid',
'qty_inner' => '70',
'qty_masterCarton' => '250',
'qty_pallet' => '270',
'averageMonthlyUnitSales' => '120',
'created_at' => '2021-12-23T11:41:31.193982+00:00'
],
[
'id' => '11102',
'sku' => 'test_3',
'asin_code' => '50',
'asin_value' => 'jl1235',
'barcode' => '10',
'barcode_value' => 'js160694',
'commodityCode' => '9989898889',
'price' => '145.99',
'picking_instruction_code' => 'PICK',
'picking_instruction_value' => 'I\'ve just had an unhappy love affair, so I don\'t see why anybody else should have a good time.',
'qty_inner' => '100',
'qty_masterCarton' => '200',
'qty_pallet' => '300',
'averageMonthlyUnitSales' => '100',
'created_at' => '2022-03-13T04:14:12.11.093745 +00:00'
],
];
I can perform the first part of the assignment (filter for averageMonthlyUnitSales>350) by carrying out something like:
$filtered_array= array_filter($data, function($item){
return ($item['averageMonthlyUnitSales']>350);
});
But I am not too sure how I can go about getting a new array in the required format?
The only way I can see to simply do both is as follows.
$data = [
[
'id' => '9947',
'sku' => 'test_1',
'asin_code' => '50',
'asin_value' => '',
'barcode' => '10',
'barcode_value' => 'js160694',
'commodityCode' => '9989898889',
'price' => '120.50',
'picking_instruction_code' => 'PICK',
'picking_instruction_value' => '',
'qty_inner' => '120',
'qty_masterCarton' => '200',
'qty_pallet' => '1200',
'averageMonthlyUnitSales' => '750',
'created_at' => '2019-02-23T01:54:14.957299+00:00'
],
[
'id' => '10921',
'sku' => 'test_2',
'asin_code' => '50',
'asin_value' => 'bx12345',
'barcode' => '10',
'barcode_value' => 'jb170931',
'commodityCode' => '9989898889',
'price' => '20.59',
'picking_instruction_code' => 'PICK',
'picking_instruction_value' => 'It\'s only half completed, I\'m afraid',
'qty_inner' => '70',
'qty_masterCarton' => '250',
'qty_pallet' => '270',
'averageMonthlyUnitSales' => '120',
'created_at' => '2021-12-23T11:41:31.193982+00:00'
],
[
'id' => '11102',
'sku' => 'test_3',
'asin_code' => '50',
'asin_value' => 'jl1235',
'barcode' => '10',
'barcode_value' => 'js160694',
'commodityCode' => '9989898889',
'price' => '145.99',
'picking_instruction_code' => 'PICK',
'picking_instruction_value' => 'I\'ve just had an unhappy love affair, so I don\'t see why anybody else should have a good time.',
'qty_inner' => '100',
'qty_masterCarton' => '200',
'qty_pallet' => '300',
'averageMonthlyUnitSales' => '100',
'created_at' => '2022-03-13T04:14:12.11.093745 +00:00'
],
];
$new = [];
foreach ($data as $line){
if ( $line['averageMonthlyUnitSales'] > 350 ){
// reformat the array
$new = [
'id' => $line['id'],
'sku' => $line['sku'],
'alternates' => ['asin' => ['code'=>$line['asin_code'], 'value'=>$line['asin_value'] ],
'barcode' => ['code'=> $line['barcode'], 'value' => $line['barcode_value']]
],
'commodityCode' => $line['commodityCode'],
'price' => [ 'value' => $line['price'] ],
'instructions' => ['picking' => ['code' => $line['picking_instruction_code'], 'value'=> $line['picking_instruction_value']]
],
'quantity' =>['inner' =>$line['qty_inner'], 'masterCarton' =>$line['qty_masterCarton'], 'pallet'=>$line['qty_pallet']],
'averageMonthlyUnitSales'=>$line['averageMonthlyUnitSales'],
'created_at'=>$line['averageMonthlyUnitSales']
];
}
}
print_r($new);
RESULT
PHP 8.1.3
Array
(
[id] => 9947
[sku] => test_1
[alternates] => Array
(
[asin] => Array
(
[code] => 50
[value] =>
)
[barcode] => Array
(
[code] => 10
[value] => js160694
)
)
[commodityCode] => 9989898889
[price] => Array
(
[value] => 120.50
)
[instructions] => Array
(
[picking] => Array
(
[code] => PICK
[value] =>
)
)
[quantity] => Array
(
[inner] => 120
[masterCarton] => 200
[pallet] => 1200
)
[averageMonthlyUnitSales] => 750
[created_at] => 750
)

PHP add values from two arrays

I have two php arrays that are in different orders. I want to find the correct array from array one and array two and add them together based on the values from currency, itemsSold and total. I also need to group them by currency and PaymentType.
First Array
array (
0 =>
array (
'currency' => 'USD',
'department' => 'Mens',
'itemsSold' => 4566,
'paymentType' => 'Cash;Card;Voucher',
'total' => 4800,
),
1 =>
array (
'currency' => 'USD',
'department' => 'womens',
'itemsSold' => 6221,
'paymentType' => 'Cash;Card;Voucher',
'total' => 9888,
),
2 =>
array (
'currency' => 'USD',
'department' => 'Home',
'itemsSold' => 20,
'paymentType' => 'Cash;Card;Voucher',
'total' => 17233,
),
3 =>
array (
'currency' => 'GBP',
'department' => 'Home',
'itemsSold' => 20,
'paymentType' => 'Voucher',
'total' => 677,
),
4 =>
array (
'currency' => 'USD',
'department' => 'Home',
'itemsSold' => 20,
'paymentType' => 'Voucher',
'total' => 17233,
)
)
Second Array
array (
0 =>
array (
'currency' => 'USD',
'department' => 'Mens',
'itemsSold' => 12,
'paymentType' => 'Cash;Card;Voucher',
'total' => 11,
),
1 =>
array (
'currency' => 'USD',
'department' => 'Home',
'itemsSold' => 20,
'paymentType' => 'Cash;Card;Voucher',
'total' => 500,
),
2 =>
array (
'currency' => 'USD',
'department' => 'womens',
'itemsSold' => 8,
'paymentType' => 'Cash;Card;Voucher',
'total' => 1277,
),
3 =>
array (
'currency' => 'GBP',
'department' => 'Home',
'itemsSold' => 20,
'paymentType' => 'Voucher',
'total' => 677,
),
4 =>
array (
'currency' => 'USD',
'department' => 'Home',
'itemsSold' => 40,
'paymentType' => 'Voucher',
'total' => 17233,
)
)
Desired Array
array (
0 =>
array (
'currency' => 'USD',
'department' => 'Mens',
'itemsSold' => 4578,
'paymentType' => 'Cash;Card;Voucher',
'total' => 4811,
),
1 =>
array (
'currency' => 'USD',
'department' => 'Home',
'itemsSold' => 40,
'paymentType' => 'Cash;Card;Voucher',
'total' => 1856,
),
2 =>
array (
'currency' => 'USD',
'department' => 'womens',
'itemsSold' => 6229,
'paymentType' => 'Cash;Card;Voucher',
'total' => 11165,
),
3 =>
array (
'currency' => 'GBP',
'department' => 'Home',
'itemsSold' => 40,
'paymentType' => 'Voucher',
'total' => 1354,
),
4 =>
array (
'currency' => 'USD',
'department' => 'Home',
'itemsSold' => 60,
'paymentType' => 'Voucher',
'total' => 34466,
)
As you can see, the values have been added together to give the total in a new array.
I have tried array_merge() but that just adds the arrays in each-other so the desired array is 6 items long, it doesn't add the values of the arrays together.
I tried looping foreach though first array and then using the index to find the items in the second array but the index changes as the arrays can be in any order.
I'm very new to programming and especially PHP, so I would appreciate a detailed answer that helps me learn it.
Thanks
Short version of code, $a1 and $a2 are your arrays:
$newarray = [];
// rebuild array so as key is unique value,
// in your case it is 'department':
foreach ($a1 as $item) {
$newarray[$item['department']] = $item;
// Or if you group by both currency and department:
$key = $item['department'] . $item['currency'];
$newarray[$key] = $item;
}
foreach ($a2 as $item) {
$department = $item['department'];
if (isset($newarray[$department])) {
$newarray[$department]['itemsSold'] += $item['itemsSold'];
$newarray[$department]['total'] += $item['total'];
}
// Or if you group by both currency and department:
$key = $item['department'] . $item['currency'];
if (isset($newarray[$key])) {
$newarray[$key]['itemsSold'] += $item['itemsSold'];
$newarray[$key]['total'] += $item['total'];
}
}
$newarray = array_values($newarray);
print_r($newarray);
Full fiddle here.

exif_read_data on PHP 7.2 doesn't return all metadata

On PHP 7.2, the built-in function exif_read_data returns different information to PHP 7.1
This is what I get when I use 7.2:
php -r 'var_export(exif_read_data("x.jpg", "ANY_TAG"));'
array (
'FileName' => 'x.jpg',
'FileDateTime' => 1543144462,
'FileSize' => 3564506,
'FileType' => 2,
'MimeType' => 'image/jpeg',
'SectionsFound' => 'ANY_TAG, IFD0, EXIF',
'COMPUTED' =>
array (
'html' => 'width="3968" height="2976"',
'Height' => 2976,
'Width' => 3968,
'IsColor' => 1,
'ByteOrderMotorola' => 1,
),
'ImageWidth' => 3968,
'ImageLength' => 2976,
'BitsPerSample' =>
array (
0 => 8,
1 => 8,
2 => 8,
),
'ImageDescription' => 'ptr',
'Make' => 'HUAWEI',
'Model' => 'STF-L09',
'Orientation' => 0,
'XResolution' => '72/1',
'YResolution' => '72/1',
'ResolutionUnit' => 2,
'Software' => 'STF-L09C432B120',
'DateTime' => '2018:11:24 15:11:58',
'YCbCrPositioning' => 1,
)
But when I run the exact same code on 7.1, I get much more EXIF data:
array (
'FileName' => 'x.jpg',
'FileDateTime' => 1543144462,
'FileSize' => 3564506,
'FileType' => 2,
'MimeType' => 'image/jpeg',
'SectionsFound' => 'ANY_TAG, IFD0, THUMBNAIL, EXIF, GPS, INTEROP',
'COMPUTED' =>
array (
'html' => 'width="3968" height="2976"',
'Height' => 2976,
'Width' => 3968,
'IsColor' => 1,
'ByteOrderMotorola' => 1,
'ApertureFNumber' => 'f/2.2',
'Thumbnail.FileType' => 2,
'Thumbnail.MimeType' => 'image/jpeg',
'Thumbnail.Height' => 384,
'Thumbnail.Width' => 512,
),
'ImageWidth' => 3968,
'ImageLength' => 2976,
'BitsPerSample' =>
array (
0 => 8,
1 => 8,
2 => 8,
),
'ImageDescription' => 'ptr',
'Make' => 'HUAWEI',
'Model' => 'STF-L09',
'Orientation' => 0,
'XResolution' => '72/1',
'YResolution' => '72/1',
'ResolutionUnit' => 2,
'Software' => 'STF-L09C432B120',
'DateTime' => '2018:11:24 15:11:58',
'YCbCrPositioning' => 1,
'Exif_IFD_Pointer' => 280,
'GPS_IFD_Pointer' => 8454,
'DeviceSettingDescription' => 'ipp' . "\0" . '',
'THUMBNAIL' =>
array (
'ImageWidth' => 512,
'ImageLength' => 384,
'Compression' => 6,
'Orientation' => 0,
'XResolution' => '72/1',
'YResolution' => '72/1',
'ResolutionUnit' => 2,
'JPEGInterchangeFormat' => 8802,
'JPEGInterchangeFormatLength' => 31647,
),
'DocumentName' => NULL,
'ExposureTime' => '30000000/1000000000',
'FNumber' => '220/100',
'ExposureProgram' => 2,
'ISOSpeedRatings' => 320,
'ExifVersion' => '0210',
'DateTimeOriginal' => '2018:11:24 15:11:58',
'DateTimeDigitized' => '2018:11:24 15:11:58',
'ComponentsConfiguration' => '' . "\0" . '',
'ShutterSpeedValue' => '298973/10000',
'ApertureValue' => '227/100',
'BrightnessValue' => '0/1',
'ExposureBiasValue' => '0/10',
'MeteringMode' => 5,
'LightSource' => 1,
'Flash' => 0,
'FocalLength' => '3950/1000',
'MakerNote' => 'Auto',
'SubSecTime' => '405238',
'SubSecTimeOriginal' => '405238',
'SubSecTimeDigitized' => '405238',
'FlashPixVersion' => '0100',
'ColorSpace' => 1,
'ExifImageWidth' => 3968,
'ExifImageLength' => 2976,
'InteroperabilityOffset' => 8424,
'SensingMethod' => 2,
'FileSource' => '',
'SceneType' => '',
'CustomRendered' => 1,
'ExposureMode' => 0,
'WhiteBalance' => 0,
'DigitalZoomRatio' => '100/100',
'FocalLengthIn35mmFilm' => 27,
'SceneCaptureType' => 0,
'GainControl' => 0,
'Contrast' => 0,
'Saturation' => 0,
'Sharpness' => 0,
'SubjectDistanceRange' => 0,
'GPSVersion' => '' . "\0" . '' . "\0" . '',
'GPSLatitudeRef' => 'N',
'GPSLatitude' =>
array (
0 => '51/1',
1 => '8/1',
2 => '49994201/1000000',
),
'GPSLongitudeRef' => 'W',
'GPSLongitude' =>
array (
0 => '2/1',
1 => '42/1',
2 => '59101467/1000000',
),
'GPSAltitudeRef' => '' . "\0" . '',
'GPSAltitude' => '7162/100',
'GPSTimeStamp' =>
array (
0 => '15/1',
1 => '11/1',
2 => '58/1',
),
'GPSProcessingMode' => 'GPS' . "\0" . '',
'GPSDateStamp' => '2018:11:24',
'InterOperabilityIndex' => 'R98',
'InterOperabilityVersion' => '0100',
)
Are there any modules or extensions or changes that I can make to get the full EXIF data when using 7.2? I'm on a shared Linux host, so have some limitations on what I can do.
This appears to be a bug in PHP - https://bugs.php.net/bug.php?id=72682 and https://abi-laboratory.pro/index.php?view=changelog&l=php&v=7.2.3
The only answer is to downgrade - or upgrade - to a version which doesn't have the bug.

Php top list from arrays [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 4 years ago.
How do you make someone who has a higher subscriberCount be sorted to the top? For example, I want to list the top 50 by subscriberCount. Currently it just sorts by the order added to $topchan1["items"]. I need to order by the highest subscriberCount.
$topchan1 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/channels?id='
.$kanalas1.'&part=snippet%2Cstatistics&key='.$API.''),true);
$videoList = array_merge($topchan1["items"],$topchan2["items"],$topchan3["items"],$topchan4["items"]);
foreach ($videoList as $key => $part) {
$sort[$key] = sort($part['statistics']['subscriberCount']);
}
array_multisort($sort, SORT_DESC, $videoList);
$i = 1;
for( $i = 0 ; $i <= count($videoList)-1 ; $i++ )
{
if(isset($videoList[$i]["statistics"]["subscriberCount"])) {
echo $videoList[$i]["statistics"]["subscriberCount"].' _ ';
}
}
how looks
array ( 0 => array ( 'kind' => 'youtube#channel', 'etag' => '"XI7nbFXulYBIpL0ayR_gDh3eu1k/Wj45BU6eiZOcR9nLVG4cXvflUNY"', 'id' => 'UCgQ1CeGtjCbkvslmG3zTAFA', 'snippet' => array ( 'title' => 'ILYA STREKAL', 'description' => 'Привет, меня зовут Илья Стрекаловский, добро пожаловать на мой канал!', 'customUrl' => 'BayanCover', 'publishedAt' => '2013-01-13T15:44:18.000Z', 'thumbnails' => array ( 'default' => array ( 'url' => 'https://yt3.ggpht.com/a-/AN66SAytpuX_75kGnsI5bvr_EkGTeQtZy3AJJXfH2w=s88-mo-c-c0xffffffff-rj-k-no', 'width' => 88, 'height' => 88, ), 'medium' => array ( 'url' => 'https://yt3.ggpht.com/a-/AN66SAytpuX_75kGnsI5bvr_EkGTeQtZy3AJJXfH2w=s240-mo-c-c0xffffffff-rj-k-no', 'width' => 240, 'height' => 240, ), 'high' => array ( 'url' => 'https://yt3.ggpht.com/a-/AN66SAytpuX_75kGnsI5bvr_EkGTeQtZy3AJJXfH2w=s800-mo-c-c0xffffffff-rj-k-no', 'width' => 800, 'height' => 800, ), ), 'localized' => array ( 'title' => 'ILYA STREKAL', 'description' => 'Привет, меня зовут Илья Стрекаловский, добро пожаловать на мой канал!', ), 'country' => 'RU', ), 'statistics' => array ( 'viewCount' => '234688406', 'commentCount' => '0', 'subscriberCount' => '2254032', 'hiddenSubscriberCount' => false, 'videoCount' => '153', ), ),
1 => array ( 'kind' => 'youtube#channel', 'etag' => '"XI7nbFXulYBIpL0ayR_gDh3eu1k/1vk-0WWcl2cpv1LO_4WQGsb2Qhk"', 'id' => 'UCMnOYmqiAQhE51l6AzEuOBA', 'snippet' => array ( 'title' => '', 'customUrl' => 'yanshelestx', 'publishedAt' => '2016-01-08T13:06:33.000Z', 'thumbnails' => array ( 'default' => array ( 'url' => 'https://yt3.ggpht.com/a-/AN66SAx6VddPszhqRGnHG48L5wVzTyf-h9lFa4F9Ig=s88-mo-c-c0xffffffff-rj-k-no', 'width' => 88, 'height' => 88, ), 'medium' => array ( 'url' => 'https://yt3.ggpht.com/a-/AN66SAx6VddPszhqRGnHG48L5wVzTyf-h9lFa4F9Ig=s240-mo-c-c0xffffffff-rj-k-no', 'width' => 240, 'height' => 240, ), 'high' => array ( 'url' => 'https://yt3.ggpht.com/a-/AN66SAx6VddPszhqRGnHG48L5wVzTyf-h9lFa4F9Ig=s800-mo-c-c0xffffffff-rj-k-no', 'width' => 800, 'height' => 800, ), ), 'defaultLanguage' => 'ru', 'localized' => array ( 'title' => 'Shelest', 'description' => 'Hello! This channel is dedicated to high-tech. I\'m a big lover of quality products for an adequate cost. The channel will express the personal opinion of the purchased goods and to listen to your words. Thank you!', ), 'country' => 'UA', ), 'statistics' => array ( 'viewCount' => '53038697', 'commentCount' => '0', 'subscriberCount' => '404844', 'hiddenSubscriberCount' => false, 'videoCount' => '123', ), ),
2 => array ( 'kind' => 'youtube#channel', 'etag' => '"XI7nbFXulYBIpL0ayR_gDh3eu1k/sSeA4B5B1NeVdRrLvhV6IQk9AJs"', 'id' => 'UCEFpNxeybzVwRbnYabQsXEg', 'snippet' => array ( 'title' => 'Bass Music Movement', 'description' => 'Music Promotion & Record Label Submissions/Business inquiries: bassmusicmovement#outlook.com', 'customUrl' => 'brazilianbassmovement', 'publishedAt' => '2017-03-06T02:48:38.000Z', 'thumbnails' => array ( 'default' => array ( 'url' => 'https://yt3.ggpht.com/a-/AN66SAx25V8TX9UzZkzfLlHPFH9yFjxQQQFeILTi=s88-mo-c-c0xffffffff-rj-k-no', 'width' => 88, 'height' => 88, ), 'medium' => array ( 'url' => 'https://yt3.ggpht.com/a-/AN66SAx25V8TX9UzZkzfLlHPFH9yFjxQQQFeILTi=s240-mo-c-c0xffffffff-rj-k-no', 'width' => 240, 'height' => 240, ), 'high' => array ( 'url' => 'https://yt3.ggpht.com/a-/AN66SAx25V8TX9UzZkzfLlHPFH9yFjxQQQFeILTi=s800-mo-c-c0xffffffff-rj-k-no', 'width' => 800, 'height' => 800, ), ), 'localized' => array ( 'title' => 'Bass Music Movement', 'description' => 'Music Promotion & Record Label Submissions/Business inquiries: bassmusicmovement#outlook.com', ), 'country' => 'BR', ), 'statistics' => array ( 'viewCount' => '136215709', 'commentCount' => '0', 'subscriberCount' => '748023', 'hiddenSubscriberCount' => false, 'videoCount' => '46', ), ),
3 => array ( 'kind' => 'youtube#channel', 'etag' => '"XI7nbFXulYBIpL0ayR_gDh3eu1k/VwnSAHbLaj-RwQW8QKFECxplCp4"', 'id' => 'UCAf-RYRpQgxpj8voC29ck7w', 'snippet' => array ( 'title' => 'Hard Play', 'description' => '', 'customUrl' => 'hardplaygamechannel', 'publishedAt' => '2016-06-23T20:39:00.000Z', 'thumbnails' => array ( 'default' => array ( 'url' => '', 'width' => 88, 'height' => 88, ), 'medium' => array ( 'url' => 'https://yt3.ggpht.com/a-/AN66SAyu2XfSQsqjyNqu-fTTjleD9XzLSLoLsP-8Yw=s240-mo-c-c0xffffffff-rj-k-no', 'width' => 240, 'height' => 240, ), 'high' => array ( 'url' => 'https://yt3.ggpht.com/a-/AN66SAyu2XfSQsqjyNqu-fTTjleD9XzLSLoLsP-8Yw=s800-mo-c-c0xffffffff-rj-k-no', 'width' => 800, 'height' => 800, ), ), 'localized' => array ( 'title' => 'Hard Play', 'description' => '', ), 'country' => 'RU', ), 'statistics' => array ( 'viewCount' => '39723260', 'commentCount' => '0', 'subscriberCount' => '784162', 'hiddenSubscriberCount' => false, 'videoCount' => '260', ), ), )
You need to use usort() with custome function where you can compare viewCount and sort array in DESC order
function sortByviewCount($a, $b) {
return ($a['statistics']['viewCount'] > $b['statistics']['viewCount']) ? -1:1;
}
usort($videoList, 'sortByviewCount');
print_r($videoList);
Output:-https://3v4l.org/HqXVc

Get values from unserialized data

I have a serialized field in my database. I can get the contents of this field and unserialize them however I am unsure how to get certain values of these. I ultimately need a foreach of each item and value from the data.
In the below example I need to be able to get the following:
Main Image Replacement:
BGL_Burhill_People_AndyHiseman_300dpi_Super-Size-14.JPG Complimentary:
Comp Text Quote Code: Code Text
I need the label as one variable and the value as another within a foreach. These labels and values are variable so I cannot manually get this data by their labels.
array (
0 =>
array (
'mode' => 'builder',
'cssclass' => '',
'hidelabelinorder' => '',
'hidevalueinorder' => '',
'element' =>
array (
'type' => 'radio',
'rules_type' =>
array (
'Reprint_0' =>
array (
0 => '',
),
'Edit Artwork_1' =>
array (
0 => '',
),
),
'_' =>
array (
'price_type' => '',
),
),
'name' => '',
'value' => 'Edit Artwork',
'price' => '',
'section' => '58073632e582b5.35893028',
'section_label' => '',
'percentcurrenttotal' => 0,
'currencies' =>
array (
),
'price_per_currency' =>
array (
'GBP' => '',
),
'quantity' => 1,
'multiple' => '1',
'key' => 'Edit Artwork_1',
'use_images' => '',
'changes_product_image' => '',
'imagesp' => '',
'images' => '',
),
1 =>
array (
'mode' => 'builder',
'cssclass' => '',
'hidelabelinorder' => '',
'hidevalueinorder' => '',
'element' =>
array (
'type' => 'radio',
'rules_type' =>
array (
'BGL_Burhill_People_AndyHiseman_300dpi_Super-Size-14.JPG_0' =>
array (
0 => '',
),
'BGL_Burhill_People_AndyHiseman_300dpi_Super-Size-21.JPG_1' =>
array (
0 => '',
),
'BGL_Burhill_People_AndyHiseman_300dpi_Super-Size-77.JPG_2' =>
array (
0 => '',
),
),
'_' =>
array (
'price_type' => '',
),
),
'name' => 'Main Image Replacement',
'value' => 'BGL_Burhill_People_AndyHiseman_300dpi_Super-Size-14.JPG',
'price' => '',
'section' => '58073632e582d2.46631826',
'section_label' => 'Main Image Replacement',
'percentcurrenttotal' => 0,
'currencies' =>
array (
),
'price_per_currency' =>
array (
'GBP' => '',
),
'quantity' => 1,
'multiple' => '1',
'key' => 'BGL_Burhill_People_AndyHiseman_300dpi_Super-Size-14.JPG_0',
'use_images' => 'images',
'changes_product_image' => '',
'imagesp' => '',
'images' => 'http://burhill.immaculate.co.uk/wp-content/uploads/2016/10/BGL_Burhill_People_AndyHiseman_300dpi_Super-Size-14-150x150.jpg',
),
2 =>
array (
'mode' => 'builder',
'cssclass' => 'col-6',
'hidelabelinorder' => '',
'hidevalueinorder' => '',
'element' =>
array (
'type' => 'textfield',
'rules_type' =>
array (
0 =>
array (
0 => '',
),
),
'_' =>
array (
'price_type' => '',
),
),
'name' => 'Complimentary',
'value' => 'Comp Text',
'price' => '',
'section' => '58073632e582f4.32183997',
'section_label' => 'Complimentary',
'percentcurrenttotal' => 0,
'currencies' =>
array (
),
'price_per_currency' =>
array (
),
'quantity' => 1,
),
3 =>
array (
'mode' => 'builder',
'cssclass' => 'col-6',
'hidelabelinorder' => '',
'hidevalueinorder' => '',
'element' =>
array (
'type' => 'textfield',
'rules_type' =>
array (
0 =>
array (
0 => '',
),
),
'_' =>
array (
'price_type' => '',
),
),
'name' => 'Quote Code',
'value' => 'Code Text',
'price' => '',
'section' => '58073632e58317.46363272',
'section_label' => 'Quote Code',
'percentcurrenttotal' => 0,
'currencies' =>
array (
),
'price_per_currency' =>
array (
),
'quantity' => 1,
),
)
foreach($your_array as $key => $value) {
$your_value = $value['value'];
$your_label = $value['section_label'];
}
This should work for you as long as i got the right keys there.

Categories