I am making an online shopping cart. so I want to update my total stock after confirming my products... I am able to catch the quantity from the user and i am able to catch my data from MYSQL. Now i want to make an array from the difference between my MYSQL quantity and user quantity and update my total stock after purchase...
My MYSQL ARRAY OUTPUT IS:
print_r($qty);
Array ( [0] => Array ( [stock] => 100 ) [1] => Array ( [stock] => 100 ) [2] => Array ( [stock] => 50 ) [3] => Array ( [stock] => 100 ) )
and
my user ARRAY OUTPUT IS:
print_r ($_SESSION['productqty']);
Array ( [0] => 10 [1] => 12 [2] => 14 [3] => 16 )
I want to make an array which will be like
Array ( [0] => 90 [1] => 88 [2] => 36 [3] => 84 )
This array is the difference between the two arrays and it will be updated in the MYSQLI Query...
I have Tried Everything. Please Help me...
If the indexes are equal the following code could work:
$remaining = [];
// iterate $qty rows and fill $remaining array
foreach($qty as $index => $entry) {
$remaining[] = $entry['stock'] - $_SESSION['productqty'][$index];
}
var_dump($remaining);
EDIT: Store updated stock in database
Firstly it's necessary to select products' ids in your first query so that you're able to update them later. This step should result the following dump (apart from the correct ids)
Array (
[0] => Array ( [id] => 12, [stock] => 100 )
[1] => Array ( [id] => 37, [stock] => 100 )
[2] => Array ( [id] => 39, [stock] => 50 )
[3] => Array ( [id] => 50, [stock] => 100 )
)
Now you can optimize your calculation by attaching the products' ids to your array:
remaining = [];
foreach($qty as $index => $entry) {
$remaining[] = [
'id_product' => $entry['id'],
'stock' => $entry['stock'] - $_SESSION['productqty'][$index]
];
}
Now you're able to store your updated stocks:
foreach($remaining as $entry) {
// Perform your SQL-Operation, something like:
// UPDATE products SET stock = $entry['stock'] WHERE id = '$entry['id']
}
Attention: Please secure your application against SQL-Injections.
Take a look at: https://en.wikipedia.org/wiki/SQL_injection
Related
I have an array that contains 3 products with attributes of "color" and "size" and the products are identified by a number ( ['code'] ).
My problem is that when i pull the data from the database I get this array that is in 6 pieces because "color" and "size" get stored in separate arrays.
My question is, how do I generate the data into an array of these 3 products with all their data in the same array.
Array(
[0] => Array
(
[code] => 123
[name] => box
[stock] => 2.00
[price] => 10.00
[color] => brown
)
[1] => Array
(
[code] => 123
[name] => box
[stock] => 2.00
[price] => 10.00
[size] => L
)
[2] => Array
(
[code] => 1234
[name] => box
[stock] => 3.00
[price] => 11.00
[color] => brown
)
[3] => Array
(
[code] => 1234
[name] => box
[stock] => 3.00
[price] => 11.00
[size] => XL
)
[4] => Array
(
[code] => 12345
[name] => box
[stock] => 4.00
[price] => 12.00
[size] => XL
)
[5] => Array
(
[code] => 12345
[name] => box
[stock] => 4.00
[price] => 12.00
[color] => gray
)
)
Expected output:
[0] => Array
(
[code] => 123
[name] => box
[stock] => 4.00
[price] => 12.00
[color] => gray
[size] => XL
)
What i'm looking to do is just combine the doubled array into one. Dont want to mess with SQL anymore - it gets attribute name in one table, attribute values from another table, code,stock,price from another table, name from another table. I know something can be done with just this array even if it will be just a temporary solution.
You can do this:
assuming your array is $products
$merged = array();
foreach($products as $product) {
if (!isset($sorted[$product['code']])) {
$merged[$product['code']] = $product;
} else {
$merged[$product['code']] = array_merge($sorted[$product['code']], $product);
}
}
Use the product code as array key and then merge the array.
If the two rows are always direct successors, with the first one holding the color field, while the latter holes the size field, you can make it easily by iterating over them in a for loop:
$maxCount = count($array);
for ($i = 1; $i < $maxCount; $i += 2) {
$array[$i - 1]['size'] = $array[$i]['size'];
unset($array[i]);
}
This will iterate over each second element of the array and add the size field to the preceding field.
If you need to have succeeding array keys afterwards you can call $arry = array_values($array);.
In case the the associated rows might not be successors you need to map them based on their code field (in case thats the primary key). You can use array_reduce() for that:
$desiredOutput = array_reduce($array, function($output, $element) {
if (!array_key_exists($element['code'], $output)) {
$output[$element['code']] = $element;
} elseif (array_key_exists('size', $element)) {
$output[$element['code']]['size'] = $element['size'];
} elseif (array_key_exists('color', $element)) {
$output[$element['code']]['color'] = $element['color'];
}
return $output;
}, []);
I have tried doing this for a while and can't wrap my head around it. I have two arrays. One array that contains sensors information called $sendatas and another that contains where those sensors are allocated to called $zones.
I want to be able to create dynamic HTML checkboxes within a table row based on whether the sensor is allocated to a zone or not and if it is then show a checked checkbox and if it isn't then show an unchecked checkbox.
Here is an example of my arrays:
The $sendatas array:
[1] => Array
(
[hwserial] => 00002025
[name] => FG05 Room Temp
[serial] => 5
[chan] => 1
[alarmhigh] => 30
[alarmlow] => 5
[delay] => 10
)
[2] => Array
(
[hwserial] => 00002025 01
[name] => FG05 Kitchen 1 Freezer
[serial] => 5
[chan] => 2
[alarmhigh] => -10
[alarmlow] => -35
[delay] => 10
)
The $zones array:
[0] => Array
(
[serial] => 1
[idGrid] => 50
[name] => All Sensors
)
[1] => Array
(
[serial] => 1
[idGrid] => 52
[name] => Food Area
)
[2] => Array
(
[serial] => 2
[idGrid] => 50
[name] => All Sensors
)
[3] => Array
(
[serial] => 2
[idGrid] => 52
[name] => Food Area
)
[4] => Array
(
[serial] => 3
[idGrid] => 50
[name] => All Sensors
)
[5] => Array
(
[serial] => 3
[idGrid] => 52
[name] => Food Area
)
[6] => Array
(
[serial] => 4
[idGrid] => 50
[name] => All Sensors
)
Both of my zones are not the same length. What I want to be able to achieve is to create an array that looks like this by finding the serial keys that match from both arrays.
Array
(
[0] => Array
(
[hwserial] => 00001216
[name] => Fridge Office Thermal
[serial] => 1
[chan] => 1
[alarmhigh] => 8
[alarmlow] => -2
[delay] => 10
[idGrid1] => 50
[idGrid2] => 51
[idGrid3] => 52
[zonename1] => All Sensors
[zonename2] => Office
[zonename3] => Food Area
)
[1] => Array
(
[hwserial] => 00002025
[name] => FG05 Room Temp
[serial] => 5
[chan] => 1
[alarmhigh] => 30
[alarmlow] => 5
[delay] => 10
[idGrid] => 50
[idGrid] => Not Used
[idGrid] => 52
[zonename1] => All Sensors
[zonename2] => Not Used
[zonename3] => Food Area
)
I am pretty sure I can write the code for the checkboxes once I have this array formatted properly. I have tried using some foreach loops but just keep making a mess of it. I have so far tried this on and off for a few weeks hoping it would just come to me but it hasn't. Any help appreciated.
Based on what you said you're trying to do with this, I think it looks like the array you're trying to create will not be that easy to work with. I think your sensors array is fine, and you just need to focus on the $zones array.
foreach ($zones as $zone) {
$zones_sensors[$zone['idGrid']]['name'] = $zone['name'];
$zones_sensors[$zone['idGrid']]['sensors'][$zone['serial']] = true;
}
This will reorganize the data in your $zones array into this format:
$zones_sensors = [
50 => ['name' => 'All Sensors', 'sensors' => [1 => true, 2 => true, 3 => true]],
51 => ['name' => 'Office', 'sensors' => [1 => true]],
52 => ['name' => 'Food Area', 'sensors' => [1 => true, 2 => true, 3 => true]]
];
This provides the two things you need to output the checkboxes as you described.
A complete list of zones
An indexed collection of serials associated with each zone.
You can use it to output headers for all the zones
foreach ($zones_sensors as $zone_id => $zone) {
// output one row with headers for zones
echo $zone['name']; // (formatting up to you)
}
Then when you output the sensors it will be easy to find which zones they're allocated to.
foreach ($sendatas as $sensor) { // make a row for each sensor
foreach ($zones_sensors as $zone_id => $zone) { // iterate the full list of zones
// check if the sensor is allocated to that zone
if (isset($zone['sensors'][$sensor['serial']])) {
// checkbox is checked
} else {
// checkbox is unchecked
}
}
}
This should just be a matter of creating a new array (let's call it $combined) that is a clone of one of the $sendatas array but uses the [serial] as a key so that you can target specific item. You would loop through the $zones array and for each item check if the [serial] is found in $combo and if a match is found inject the [idgrid] and [name] as a sub array for $combined['serial']. As you have not used sub array you could add a counter to add an incrementing number of values.
Something along the lines of this should do the trick:
$results = [];
foreach ($sendatas as $sensor) {
$zone_counter = 0;
foreach ($zones as $zone) {
if ($zone['serial'] == $sensor['serial']) {
$zone_counter++;
$sensor['idGrid' . $zone_counter] = $zone['idGrid'];
$sensor['zonename' . $zone_counter] = $zone['name'];
}
}
$results[] = $sensor;
// if you only want $results to contain sensors that actually have zones,
// wrap it in an if-statement:
// if ($zone_counter > 0) {
// $results[] = $sensor;
// }
}
print_r($results);
Note that this won't give you any sensors with matching zones with the data you provided, because those two sensors both have [serial] => 5 and all your zones have [serial] => 1 through 4. If you want to match by some other key instead of serial, just change the if-statement.
I wish to update a single product quantity from a session with a new value using php.
How can I do this.
Array data is as displayed
Array
(
[products] => Array
(
[0] => Array
(
[name] => Ford AA Flatbed
[code] => IWV001
[qty] => 1
[price] => 15.00
[weight] => 0.12
)
[1] => Array
(
[name] => Ford AA Stakebed
[code] => IWV003
[qty] => 1
[price] => 15.00
[weight] => 0.21
)
)
)
any help would be most appreciated.
I want to be able to search through the session and find the product by code and update the quantity within that product.
Something like this:
foreach($products as &product) {
if ($product[code] == $codeToUpdate) {
$product[qty] = $newQty;
}
}
Of course, this is a sequential search so it will be slow for large data sets.
I have the following array :
Array
(
[0] => Array
(
[Name] => first_data
[building] => A
[apt] => 16
)
[1] => Array
(
[Name] => first_data
[building] => B
[apt] => 16
)
[2] => Array
(
[Name] => second_data
[building] => A
[apt] => 17
)
[3] => Array
(
[Name] => second_data
[building] => B
[apt] => 18
)
and I need it to be returned as :
Array
(
[0] => Array
(
[Name] => first_data
[A] => 16
[B] => 16
)
[1] => Array
(
[Name] => second_data
[A] => 17
[B] => 18
)
Any ideas?
BTW the first array has hundreds of entries (not only first_data, but second and etc...) plus it has more than A and B.
Thanks in advance.
Not exactly what you want, but if you instead index the new array by the name, you can do this very easily. If the index number is some kind of ID, you can just create a field for it
foreach ( $oldarray as $index => $piece )
{
$newarray[$piece['Name']] = array($piece['building'] => $piece['apt'])
}
This will give you
Array
(
['first_data'] => Array
(
['A'] => 16,
['B'] => 16
)
['second_data'] => Array
(
['A'] => 17,
['B'] => 18
)
)
Since you have two entries with the same new, when you hit the 2nd loop, it will simply add the other building name. If you can work with this layout, then your solution is very easy, it will take more steps to do it exactly as you showed. If you absolutely have to do it the way you showed, you need extra code to loop through the new array, find the building name, add the key in the correct place, but this will be slower if you have a large amount of data.
In my opinion, the way I presented it is a far easier way to look around the array too. If you wanted to know the apt value for A in "second_data" you can just do
$newarray['second_data']['A']
with your array layout, it would require a loop to search the array for "second_data" because you have no idea where it is.
I have a PHP array question regarding searching which I'm hoping some kind person can help me with...
The array shown below is an collection of arrays, e.g. order items. As I loop a separate array of orderIds I would like to return the appropriate array of products.
For example, if I request an orderId of 98305 it would return the arrays with the indexes of 2 & 3.
Are there any PHP functions to do this? I could loop each array and check the value and break out when it matches, but I feel this brings quite an overhead of performing multiple loops per orderId lookup.
Array
(
[0] => Array
(
[orderId] => 98303
[product] => Product A
)
[1] => Array
(
[orderId] => 98304
[product] => Product B
)
[2] => Array
(
[orderId] => 98305
[product] => Product C
)
[3] => Array
(
[orderId] => 98305
[product] => Product D
)
[4] => Array
(
[orderId] => 98306
[product] => Product A
)
[5] => Array
(
[orderId] => 98306
[product] => Product B
)
)
Any help appreciated.
D
array_filter()
$output = array_filter($input,function($a) {
return $a['orderId'] == 98305;
});
Replace 98305 with the desired ID.