duanqian9503 2017-11-03 19:59
浏览 7
已采纳

如何检查数组的键值以防止在php中重复输入?

I know this is a very common and repeated subject, but after spending some hours of googling I didn't find the right solution for my problem.

Using a foreach loop I'm filling an array, each row including a key and value. I just want to prevent duplicates or remove them.

$data['products'] = array();
$data['stores'] = array();

foreach ($products as $product) {
    //if (!in_array($product['store_id'], $data['stores'])) {
    if (!array_key_exists($product['store_id'], $data['stores'])) {
        $data['stores'][] = array(
            'store_id'   => $product['store_id'],
            'store_name' => $product['store_name']
        );
    }
}

The result of print_r($data['stores']):

Array
(
    [0] => Array
        (
            [store_id] => 1
            [store_name] => Karaca
        )

    [1] => Array
        (
            [store_id] => 1
            [store_name] => Karaca
        )

    [2] => Array
        (
            [store_id] => 7
            [store_name] => nurteks
        )

    [3] => Array
        (
            [store_id] => 7
            [store_name] => nurteks
        )
)

I tried all suggestions, but I don't know how to figure it out.
Thanks for any kind help!

  • 写回答

2条回答 默认 最新

  • duanning9110 2017-11-03 20:03
    关注

    Use the store ID as the key in the stores array. This will ensure that the entries are unique since array keys are inherently unique.

    foreach ($products as $product) {
        $data['stores'][$product['store_id']] = array(
            'store_id'   => $product['store_id'],
            'store_name' => $product['store_name']
        );
    }
    

    The two things you tried didn't work because:

    1. if (!in_array($product['store_id'], $data['stores'])) {...
      The "needle" ($product['store_id']) is an integer, but the "haystack" ($data['stores']) contains arrays.

    2. if (!array_key_exists($product['store_id'], $data['stores'])) {
      You aren't specifying array keys when you use $data['stores'][] to append items, so the store id won't be found as an array key, or if it is, it won't really be the store id, it will just be the automatically assigned sequential index that just coincidentally matches a store id.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥150 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装