duanqian9503 2017-11-03 11: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 12: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部