我正在使用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/