dongzai2952 2018-01-12 11:16
浏览 66
已采纳

在php和wordpress中合并然后排序2个数组

I'm trying to merge 2 arrays in PHP and then sort them.

I'm pulling data from WordPress database ( tags and categories ) and I need to merge them and sort them properly.

Code looks similar to this:

$categories = [ 
  '<a>WordPress Tips</a>',
  '<a>SEO Tips'</a>, 
  '<a>Development Tips</a>' 
]; 

$tags = [ 
  '<a>WordPress</a>',
  '<a>SEO'</a>, 
  '<a>Development</a>' 
]; 

$taxonomies = array_merge($categories, $tags);
sort($taxonomies);

Since I need to loop through $taxonomies array and print them with anchors included ( every one of those must have a valid URL to itself ), I don't get a proper sorting result. However, as soon as I 'strip out' all the tags around these items, sorting works as it should, but I don't get URLs that I need, only string / text.

Could someone suggest a better sorting algorithm which would sort these items properly with html elements included around them? Thanks!

  • 写回答

2条回答 默认 最新

  • duanci19881003 2018-01-12 11:41
    关注

    You need to do custom comaprision to make it work using usort() and strip_tags()

    <?php
    $taxonomies = array_merge($categories, $tags);
    print_r($taxonomies);
    function cmp($a, $b){
        $data1 = strip_tags($a);
        $data2 = strip_tags($b);
        return ($data1 < $data2) ? -1 : 1;
    }
    usort($taxonomies, "cmp");
    print_r($taxonomies);
    

    Output:-https://eval.in/934071

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)