PHP 搜索过滤器按字母顺序对结果排序
PHP Search filter sort results alphabetically
我正在开发一个带有搜索功能的小型网络目录。我在 Joomla 中使用 Eshop 软件。有制造商筛选功能,但这些结果不是按字母顺序显示的。
我四处寻找解决方案,但我无法让它工作。这是代码:
<?php
if (!empty($filterData['manufacturer_ids'])){
$manufacturerIds = $filterData['manufacturer_ids'];
}
else{
$manufacturerIds = array();
}
foreach ($manufacturers as $manufacturer){?>
<li>
<label class="checkbox">
<input class="manufacturer" onclick="eshop_ajax_products_filter('manufacturer');" type="checkbox" name="manufacturer_ids[]" value="<?php echo $manufacturer->manufacturer_id; ?>" <?php if (in_array($manufacturer->manufacturer_id, $manufacturerIds)) echo 'checked="checked"'; ?>>
<?php echo $manufacturer->manufacturer_name; ?><span class="badge badge-info"><?php echo $manufacturer->number_products;?></span>
</label>
</li>
<?php }?>
谁能帮帮我?
您可以使用 sort
函数,我建议使用 SORT_STRING
可选参数为您提供以下内容。
$manufacturers = sort($manufacturers, SORT_STRING);
This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.
...
SORT_STRING - compare items as strings
编辑:
确认数据结构后,这是一个对象数组,需要自定义排序功能。因此,您应该使用 usort()
.
This function will sort an array by its values using a user-supplied
comparison function. If the array you wish to sort needs to be sorted
by some non-trivial criteria, you should use this function.
因此,您首先定义比较 manufacturer_name
属性.
字符串的函数
function cmp($a, $b)
{
return strcmp($a->manufacturer_name, $b->manufacturer_name);
}
usort($manufacturers , "cmp");
我正在开发一个带有搜索功能的小型网络目录。我在 Joomla 中使用 Eshop 软件。有制造商筛选功能,但这些结果不是按字母顺序显示的。
我四处寻找解决方案,但我无法让它工作。这是代码:
<?php
if (!empty($filterData['manufacturer_ids'])){
$manufacturerIds = $filterData['manufacturer_ids'];
}
else{
$manufacturerIds = array();
}
foreach ($manufacturers as $manufacturer){?>
<li>
<label class="checkbox">
<input class="manufacturer" onclick="eshop_ajax_products_filter('manufacturer');" type="checkbox" name="manufacturer_ids[]" value="<?php echo $manufacturer->manufacturer_id; ?>" <?php if (in_array($manufacturer->manufacturer_id, $manufacturerIds)) echo 'checked="checked"'; ?>>
<?php echo $manufacturer->manufacturer_name; ?><span class="badge badge-info"><?php echo $manufacturer->number_products;?></span>
</label>
</li>
<?php }?>
谁能帮帮我?
您可以使用 sort
函数,我建议使用 SORT_STRING
可选参数为您提供以下内容。
$manufacturers = sort($manufacturers, SORT_STRING);
This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.
...
SORT_STRING - compare items as strings
编辑:
确认数据结构后,这是一个对象数组,需要自定义排序功能。因此,您应该使用 usort()
.
This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
因此,您首先定义比较 manufacturer_name
属性.
function cmp($a, $b)
{
return strcmp($a->manufacturer_name, $b->manufacturer_name);
}
usort($manufacturers , "cmp");