使用特定要求重新排序阵列

时间:2015-06-04 18:02:39

标签: php algorithm

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

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

  • 但如果我们有这个" casa-cocina-mesas-somethingelse - "这个" casa-anotherstuff-mesas-somethingelse - ",两者都必须保存。

  • 如果某个值具有另一个不同的值,例如" electronic-tools"和"电子计算机配件"。必须保存bot数组。

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

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

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

1 个答案:

答案 0 :(得分:0)

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

<?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"
// }