php - 使用特定要求重新排序数组

标签 php algorithm

我有一个不需要像这样重新排序的数组:

  • 如果这个有“casa-cocina-mesas-”和“casa-cocina-mesas-somethingelse-”,值多的必须保留,另一个必须删除。

    <
  • 但是如果我们有这个“casa-cocina-mesas-somethingelse-”和这个“casa-anotherstuff-mesas-somethingelse-”,则两者都必须保存。

  • 如果一个值有另一个不同的值,如“electronic-tools”和“electronic-computer-accessory”。 bot数组必须保存。

  • 我也有一些值为空,但这个值并不重要。

  • 最后必须删除所有其他的。

    <?php
    $category = array("casa-cocina-",null,"casa-","electronic-computer-accessory","electronic-",null,"casa-cocina-mesas-",
    "casa-cocina-","electronic-","electronic-tools");
    ?>
    

最佳答案

对于每个值,您想知道该字符串是否包含在数组中已存在的另一个值中。如果是,我们可以忽略该值。以下应该可以解决问题:

<?php
$categories = array("casa-cocina-",null,"casa-","electronic-computer-accessory","electronic-",null,"casa-cocina-mesas-","casa-cocina-","electronic-","electronic-tools");

// Remove empty values from your array
$categories = array_filter($categories);

$temp = [];

$element = array_shift($categories);

while ($element != NULL) {
    $found = false;
    // Check the remaining elements in the array
    foreach ($categories as $category) {
        if (strpos($category, $element) !== FALSE) {
            // We found this as a substring
            $found = true;
            break;
        }
    }

    if (!$found) {
        // Check the elements in the temp array to prevent duplication.
        foreach ($temp as $category) {
            if (strpos($category, $element) !== FALSE) {
                // We found this as a substring
                $found = true;
                break;
            }
        }
    }

    // If we didn't find the value as a substring, add it to $temp
    if (!$found) {
        $temp[] = $element;
    }

    // Pull the next element from the array
    $element = array_shift($categories);
}

// Store the processed array
$categories = $temp;

echo var_dump($categories);

// array(3) {
//   [0]=> string(29) "electronic-computer-accessory"
//   [1]=> string(18) "casa-cocina-mesas-"
//   [2]=> string(16) "electronic-tools"
// }

关于php - 使用特定要求重新排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30650997/

相关文章:

javascript - 在输入文本中搜索然后搜索结果将使用 Ajax PHP 出现在下拉列表中

java - 模拟退火 TSP

algorithm - 如何在minimax算法中获取子节点的值?

java - 给定邻接规则和未排序数组,返回符合规则的数组

r - 如何分解一个大整数

algorithm - 寻找算法(低内存占用): Toggling lights

PHPmailer AddEmbeddedImage 嵌入图像失败

php - 如何上传 JSON 文件以在 Javascript 运行时创建对象而不更改服务器端脚本?

php - 将 MySQL 数据调用到下拉列表中

php - 解析电子邮件附件的脚本