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条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败