English 中文(简体)
加入联系阵列——但不重复
原标题:Add to associative array -- but no duplicates
  • 时间:2012-04-16 01:16:21
  •  标签:
  • php
  • arrays

我的目标是将一套新的产品记录贴在现有的联系阵列,但确保每个产品只代表一次。 我写了以下职能。 对于这种简单的东西,它似乎太大。 是否有PHP阵列功能,我需要了解吗?

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; }
    }
}
最佳回答

利用产品识别作为钥匙,例如$already[$result[ Products_id]] = result;,然后,您可以使用array_key_exists,以方便对照所有现有产品核对产品。 (要么,要么,要么,要么,要么,要么,你只拥有一个产品,如果你不检查,最新的重复就会超过以前的重复。)

不管怎样,你都会完全删除<条码>。

function _append(&$already, $addition) {
    while ($result = mysql_fetch_array($addition)) {
        if (!array_key_exists($result[ products_id ], $already)) {
            $already[$result[ products_id ]] = $result;
        }
    }
}

渔获量是,你的阵列已不再以数字指数化。 在您添加物品的情况下,请添加其钥匙(产品价值_id)。 但你可以说,<条码>各条(项目为)。

问题回答

How about assigning the product id as the array key in $already?

while( $result = mysql_fetch_array( $addition ) ) {
  $already[$result[ products_id ]] = $result;
}

这当然会超越旧产品记录,但应当避免重复!





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签