我有一个不需要像这样重新排序的数组:
如果这个有“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/