I need to remove the duplicate data from this array, to insert it into a database.
You can see that there are 2 duplicate products, tv.
I need to remove the duplicates from the array, but I also want the quantity columns to be summed.
I found that there is an array method array_unique(),
it removes the duplicate but I need the quntity columns to be added.
It is highly possible that there is something like this already made, so I ask.
function sanitize_deep($array) {
foreach($array as $k=>$v) {
if (is_array($v)) {
$array[$k] = sanitize_deep($v);
} else {
$array[$k] = mysql_real_escape_string($v);
}
}
return $array;
}
Should do the trick. It’s a recursive function that can take up as many dimensions as you like (i.e., unlimited)
For displaying data you can start as simple as using the strip_tags, htmlentities, and/or several regex (preg_match, preg_replace) functions, or go all out and use something like HTMLPurifier
Thanks for the replies, I used the database method, but with a for loop.
Sorry, for the double post I accidentaly made.
Is there a method I could sanitize a multidimensional array?
I think I could use what ScallioXTX supposed:
(However It creates an new array then, or I could modify it)
foreach($products as $product) {
$product = array_map('mysql_real_escape_string', $product);
...
Also, the mysql_real_escape_string indicates MySQL database,
what sanitizing methods should I use for displaying data in HTML?
I guess there shouldn’t be much difference but there could be subtleties.
I would advise against such blanket treatment of data. Sanitizing functions like this push the sanitization higher up the chain (generally) and make no effort to do anything other than the most rudimentary escaping.
Further to logic_earth’s example, assuming you cannot take the MySQL approach (why?), you could use a helper array to keep track of whether the product has been seen in the loop or not and act accordingly.
$products = array( array( "tv", 125, 11 ), array( "pc", 115, 7 ), array( "tv", 125, 4 ) );
$new_products = array();
$seen = array();
foreach ($products as $product) {
list($prod,,$quantity) = $product;
// New product, keep track of it
if (!isset($seen[$prod])) {
$seen[$prod] = count($new_products);
$new_products[] = $product;
// We've seen this product before, bump the quantity
} else {
$new_products[$seen[$prod]][2] += $quantity;
}
}
var_dump($new_products);
I tried your method, but it returns me a empty array, what could be the problem?
I’m not good yet at debugging techniques, is there a good software for this?