php - 防止数组重复

标签 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 个条目。

我知道这很简单,但我只是想念它......

最佳答案

您可以简单地使用另一个 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
        );
}

关于php - 防止数组重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18708709/

相关文章:

php - 我正在尝试通过使用 php 调整图像大小将图像放入 div。但它不起作用

mysql - 非常规字符的不正确字符串值错误

php - 重复表条目错误

JavaScript 函数由 3 个函数组成

php - 数组的计数给出了错误的值

javascript - 如何停止回显未格式化的 json 数组

php发送具有崩溃文本文件的电子邮件

php - 在 Eloquent Model Observer 中使用 Request

javascript - 显示/隐藏 SQL 数据库中的动态 ID

php - 如何使用 PHP 从 MySQL 数据库中存储和检索图像?