为了账号安全,请及时绑定邮箱和手机立即绑定

删除数组foreach mysql中的重复项

删除数组foreach mysql中的重复项

PHP
www说 2021-11-13 17:22:30
如何创建没有重复名称的数组?$sqla = "SELECT * from categoriesb";$id = $mysql->Execute($sqla);foreach ($id as $keys) {    $sqlb = "SELECT * from productsb where parent = ".$keys["id"]."";    $cac = $mysql->Execute($sqlb);    foreach ($cac as $key) {        $tab[] = array("name" => $keys["name_c"],                        array("product" => $key["name"]));    }}我的阵列看起来像这样var_dump($tab);array(2) {[0]=> array(2) {   ["name"]=> string(10) "Beer"   [0]=> array(1) {       ["product"]=> string(13) "Mild"   }}[1]=> array(2) {   ["name"]=> string(10) "Beer"   [0]=> array(1) {       ["product"]=> string(13) "Bitter"   }}如何删除阵列上的重复名称?我想创建数组array(1) {[0]=> array(2) {    ["name"]=> string(10) "Beer"    [0]=> array(1) {       ["product"]=> string(13) "Mild"    }    [1]=> array(1) {       ["product"]=> string(13) "Bitter"    }}
查看完整描述

2 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

使用 array_unique 函数避免列表中的重复

使用 array_unique 函数避免列表中的重复


查看完整回答
反对 回复 2021-11-13
?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

注意:您的查询存在N+1 问题。


如果 id 是用户生成的字符串,它也可能遭受二次 SQL 注入。


这是一个潜在的解决方案:


$sqla = "SELECT * from categoriesb";

$categories = $mysql->Execute($sqla);

$ids = array_column($categories, 'id');

// Query with parameters

$sqlb = "SELECT * from productsb where parent IN (".implode(',', array_fill(0, count($ids), '?')).")";

// Not exactly sure what API is used here but this needs to execute the query that uses the $ids as the parameters

$products = $mysql->Execute($sqlb, $ids); 


foreach ($categories as $category) {

    $tab[$category['id']] = [ "name" => $category["name_c"] ];

}

foreach ($products as $product) {

    $tab[$product['parent']][] = array("product" => $product["name"]));

}

这会:

  1. 执行一次查询以获取所有类别

  2. 执行一个查询以获取所有相关产品,但仅针对检索到的类别(在您的情况下,一个简单的方法select *可以工作,但如果您稍后需要向第一个选择添加过滤器,则需要缩小范围

  3. 使用类别构建数组并将 id 设置为键(供以后查找)

  4. 根据产品更新数组

它总是只执行 2 次查询而不是 1 + 产品数量,如果您使用准备好的语句,您还可以避免第二次订单注入(如果这可能是一个问题,通常如果id不是用户定义的,那么它可能不会成为问题)


查看完整回答
反对 回复 2021-11-13
  • 2 回答
  • 0 关注
  • 124 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号