php - 如果 PHP 中存在数组,则跳过添加到数组

标签 php arrays

我正在使用in_array函数跳过将相同地址添加到数组中。

代码:

$addresses_list = array();
$stmt_select_address_result = $databaseManager->connect()->prepare("SELECT lat,lng,address FROM api_order where userid=683;");
$stmt_select_address_result->execute();

while ($row = $stmt_select_address_result->fetch(PDO::FETCH_ASSOC)) {
    if (!in_array($row, $addresses_list)) {
        array_push($addresses_list, $row);
    }
}

如果$row['address'],我想跳过添加到数组与 $addresses_list['address'] 的地址相同.

最佳答案

您可以创建一个临时变量来存储已存储在 $addresses_list 数组中的 address 值。每当您在 $addresses_list 数组中存储 $row 时,都可以将 address 键值存储在临时变量中。

现在,每次您需要检查临时变量,键值是否已经存在。

请注意,甚至 PHP documentation建议对 array_push() 使用 [] 运算符。所以我更改了您的代码以使用 [] 代替。

Note: If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.

尝试以下(评论中的说明):

$addresses_list = array();
$temp_addresses = array(); // Create a temp array

$stmt_select_address_result = $databaseManager->connect()->prepare("SELECT lat,lng,address FROM api_order where userid=683;");
$stmt_select_address_result->execute();

while ($row = $stmt_select_address_result->fetch(PDO::FETCH_ASSOC)) {

    // check in temporary variable instead
    if (!in_array($row['address'], $temp_addresses)) {

        // add to temp array to avoid duplicate entry in next loop
        $temp_addresses[] = $row['address'];

        $addresses_list[] = $row;
    }
}

如果您确实只需要唯一地址值,并且重复行没有其他用途。您可以在 SQL 查询端本身解决这个问题。您只需在 address 上使用 GROUP BY 即可。这将优化从数据库服务器传输到 PHP 应用程序的数据包。此外,还可以使用其他数组操作来完成。

$addresses_list = array();

// It is a good practice to have query string in a separate variable
$sql = "SELECT lat,lng,address 
        FROM api_order 
        where userid=683 
        GROUP BY address;"

$stmt_select_address_result = $databaseManager->connect()->prepare($sql);

$stmt_select_address_result->execute();

while ($row = $stmt_select_address_result->fetch(PDO::FETCH_ASSOC)) {
    // No need for any checks, as you are getting unique addresses only        
    $addresses_list[] = $row;
}

关于php - 如果 PHP 中存在数组,则跳过添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53237974/

相关文章:

php - 使用 Graph API 在 Facebook 照片中进行偏移(超过 25 张照片)

php - 网络游戏如何将玩家联系在一起?

java - 从对象转换为字节数组并在 Java 中返回

c - 求和在给定范围内的数组中的连续子序列数的递归函数

php - 使用 ajax 在点击时编辑特定的 div

javascript - 如何使用 PHP 设置任何 jQuery 图表数据

php - 为什么我的查询不执行?

javascript - 充满对象的数组没有长度

将字符串转换为数组然后再返回时的 Javascript 问题

python - 如何将字符串放入数组