[英]Sort array alphabetically in PHP
I'm creating a website for a book publishing company. 我正在为一家图书出版公司创建一个网站。 They've books in multiple different languages and want to display some details for each language.
他们有多种不同语言的书籍,并希望显示每种语言的一些详细信息。 To retrieve all the necessary information for each language, I do the following:
要检索每种语言的所有必要信息,请执行以下操作:
<div class="col-lg-3" align="center">
<?php
$fields = get_field_objects();
if ($fields):
foreach ($fields as $name => $field):
if (stripos($name, 'isbn') !== false) : ?>
<?php $lang = substr($field['name'], strpos($field['name'], "_")); ?>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#collapse1<?php echo $lang ?>">Deutsch/<?php echo substr($field['label'], strpos($field['label'], " ") + 1); ?></a>
</h4>
</div>
<div id="collapse1<?php echo $lang ?>" class="panel-collapse collapse">
<div class="panel-body">
// ... get all neccessary information ...
</div>
</div>
</div>
</div>
<?php endif;
endforeach;
endif; ?>
</div>
Now my problem is, that if somebody creates a book, forgets to add a language and wants to add it after the book has been saved to the database, the alphabetical order is not correct anymore. 现在我的问题是,如果有人创建了一本书,却忘记添加一种语言,而是想在将本书保存到数据库之后添加它,那么字母顺序就不再正确了。 Therefore I'd like to add a sorting function for the $fields array.
因此,我想为$ fields数组添加一个排序功能。
sort($fields) doesn't work since after doing this, everything is blank. sort($ fields)不起作用,因为执行此操作后,所有内容均为空白。
Here's a screenshot of how the output looks like. 这是输出外观的屏幕截图。
And sometimes, the order is wrong (eg Deutsch/English appears on the bottom). 有时,顺序是错误的(例如,德语/英语出现在底部)。 So I'll have to sort the part where I add the second language (next to German).
因此,我必须对添加第二种语言(德语附近)的部分进行排序。 The part where I add this is here:
我添加的部分在这里:
<h4 class="panel-title">
<a data-toggle="collapse" href="#collapse1<?php echo $lang ?>">Deutsch/<?php echo substr($field['label'], strpos($field['label'], " ") + 1); ?></a>
</h4>
Does anyone have any ideas? 有人有什么想法吗? Please let me know if code is missing!
请让我知道代码是否丢失!
PS the plugin I use is "Advanced-Custom-Fields" and the functions like eg "get_field_objects()" come with that plugin! PS我使用的插件是“ Advanced-Custom-Fields”,该插件附带诸如“ get_field_objects()”之类的功能!
get_field_objects()
returns an array of custom field objects. get_field_objects()
返回自定义字段对象的数组。 You can sort it alphabetically using uasort
like this: 您可以使用
uasort
按字母顺序对其进行排序,如下所示:
$fields = get_field_objects();
uasort($fields,"sort_alphabetically");
function sort_alphabetically($a,$b) {
return $a['name'] > $b['name'];
}
So what solve my problem is @LeoTahk 's suggestion of adding ksort(). 所以解决我问题的是@LeoTahk建议添加ksort()。
Final code: 最终代码:
<div class="col-lg-3" align="center">
<?php
$fields = get_field_objects();
//working solution
ksort($fields);
if($fields):
....
endif; ?>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.