防止数组中的重复

时间:2013-09-09 23:43:21

标签: php mysql arrays

我有一个数组,我从MySQL数据库中取出,我需要将其重新格式化为另一个数组,而不会在特定键上重复。

原始阵列:

Array // $categories array
(
    [0] => Array
        (
            [name] => Body & Bath Products
            [keyword] => body-and-bath-products
        )
    [more ...]
)

新阵列结构:

Array // $links array
(
    [0] => Array
        (
            [keyword] => Body & Bath Products
            [link] => ./Body-and-Bath-Products
            [target] => _self
            [tooltip] => 1
        )
    [more ...]
)

使用PHP循环:

$links = array();

foreach ($categories as $cat):
    if (in_array ($cat['name'], $links)):
        continue;
    else:
        $links[] = array(
            'keyword' => $cat['name'],
            'link' => './' . $this->url->cap_keyword($cat['keyword']),
            'target' => '_self',
            'tooltip' => true
        );
    endif;
endforeach;

但这不起作用,仍在我的$links数组中获取所有534个条目。

我知道这很简单,但我只是错过了......

2 个答案:

答案 0 :(得分:1)

你可以简单地使用另一个foreach循环...

$links = array();

foreach ($categories as $cat){

    foreach($links as $value){ // Loop through $links array
        if($value['keyword'] == $cat['name']) // Check if $cat['name'] is already in $links
            continue 2; // Skip rest of this loop and parent loop if it exists
    }


    $links[] = array(
        'keyword' => $cat['name'],
        'link' => './' . $this->url->cap_keyword($cat['keyword']),
        'target' => '_self',
        'tooltip' => true
        );
}

答案 1 :(得分:0)

您配对的问题是您使用索引键填充$ links数组,当您检查所述数组中是否存在键时,您使用$ cat ['name']变量作为键。因为在$ links数组中实际上永远不会有重复项。

$links = array();

foreach ($categories as $cat):
    if (in_array ($cat['name'], $links)): // HERE YOU CHECK IF $links CONTAINS $cat['name'] HOWEVER YOU NEVER STORE $cat['name'] AS KEY
        continue;
    else:
        $links[] = array( // HERE YOU STORE EACH ENTRY WITH KEY AS INDEX FROM 0 TO N
            'keyword' => $cat['name'],
            'link' => './' . $this->url->cap_keyword($cat['keyword']),
            'target' => '_self',
            'tooltip' => true
        );
    endif;
endforeach;

解决方案是使用$ cat ['name']而非索引号来存储密钥     $ links = array();

foreach ($categories as $cat):
    if (array_key_exists ($cat['name'], $links)): 
        continue;
    else:
        $links[$cat['name']] = array( // You should save the entry using $cat['name'] as key for the entry this way when you do the in_array check you can prevent duplicates
            'keyword' => $cat['name'],
            'link' => './' . $this->url->cap_keyword($cat['keyword']),
            'target' => '_self',
            'tooltip' => true
        );
    endif;
endforeach;

您需要使用带键的$ cat ['name']和in_array()方法将数字键替换为array_key_exists()方法。

in_array()的问题是它检查顶部数组$ links的值,而$ links永远不会包含$ cat ['name']作为值,因为它是数组和数组。然而,$ links中的数组确实包含$ cat ['name']。