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

I have an array that I need no reorder like this:

  • If this have "casa-cocina-mesas-" and "casa-cocina-mesas-somethingelse-", the value with more values must keep it, the other must be deleted.

  • But if we have this "casa-cocina-mesas-somethingelse-" and this "casa-anotherstuff-mesas-somethingelse-", the both must be saved.

  • And if an value have another differtent value like "electronic-tools" and "electronic-computer-accessory". bot array must be saved.

  • And i have some values as null too but this value doesn't matter.

  • Finally all the other must be removed.

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

For each value, you want to know if the string is contained in another value already present in the array. If it is, we can disregard the value. The following should do the trick:

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