My goal is to append a new set of product records to an existing associative array, but ensure each product is represented only once. I wrote the function below. It looks like way too much code for something this simple. Is there a PHP array function I need to learn about?
function _append ( &$already, $addition ) {
while( $result = mysql_fetch_array( $addition ) ) {
$already_found = FALSE;
foreach ( $already as $try ) {
if ( $try["products_id"] == $result["products_id"] ) {
$already_found = TRUE;
break;
}
}
if ( !$already_found ) { $already[] = $result; }
}
}
Use the product ID as the key, like $already[$result['products_id']] = $result;
, and then you can use array_key_exists
to check the product ID easily against all the existing products. (Or, don't. Either way, you'll only have one product per ID; if you don't check, the latest duplicate will overwrite earlier ones.)
Either way, you get rid of the foreach
altogether.
function _append(&$already, $addition) {
while ($result = mysql_fetch_array($addition)) {
if (!array_key_exists($result['products_id'], $already)) {
$already[$result['products_id']] = $result;
}
}
}
The catch is, your array is no longer numerically indexed. Wherever you add items to it, you add them with their key (the value of products_id). But you can say foreach ($items as $item)
just like always.
How about assigning the product id as the array key in $already
?
while( $result = mysql_fetch_array( $addition ) ) {
$already[$result['products_id']] = $result;
}
This will of course overwrite the old product record, but it should gracefully avoid duplicates!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.