【问题标题】:Sorting an array in PHP when the second and third value are known [duplicate]当第二个和第三个值已知时,在PHP中对数组进行排序[重复]
【发布时间】:2014-09-23 12:12:23
【问题描述】:

我想对一个总是包含三个对象的数组进行排序。

脚本知道应该返回第二个和第三个对象的名称值。

如何对这个数组进行排序以确保顺序正确?

$categories = Array ( 

[48] => stdClass Object ( 
    [term_id] => 48 
    [name] => Hello 
    [term_group] => 0 
    [term_taxonomy_id] => 57 
    [taxonomy] => resume_category 
    [description] => 
    [parent] => 0 
    [count] => 572 
    [object_id] => 18397 
    [filter] => raw 

) 

[64] => stdClass Object ( 

    [term_id] => 64 
    [name] => World 
    [term_group] => 0 
    [term_taxonomy_id] => 75 
    [taxonomy] => resume_category 
    [description] => 
    [parent] => 0 
    [count] => 22 
    [object_id] => 18397 
    [filter] => raw

)

[5] => stdClass Object ( 
    [term_id] => 5 
    [name] => Test 
    [term_group] => 0 
    [term_taxonomy_id] => 75 
    [taxonomy] => resume_category 
    [description] => 
    [parent] => 0 
    [count] => 22 
    [object_id] => 5 
    [filter] => raw  

)

我希望 Hello 作为第二个值,World 作为最后一个值,但是数组的值和顺序是动态的并且会有所不同:

   foreach ( $categories as $category ) {
    echo $category->name;
    echo ', ';
   }

应该返回:test、hello、world

【问题讨论】:

  • 自定义排序任务? usort()
  • 你能提供一个样本数组并解释你想要的排序算法吗?即:按键 2 上的字母顺序。
  • 在第一行,“hello”和“world”都是小写的。最后,第一个字母大写。大小写对排序很重要。除非值为“test”,否则您是否打算对这些值进行 ucwords?
  • foreach ( $categories as $category ) : echo $category->name; endif; 您的示例类别应该是一个数组,endif 应该是 endforeach
  • 您是否尝试将名称 = 'hello' 的对象移动到位置 2 并将名称 = 'world' 的对象移动到位置 3?你的问题很不清楚!

标签: php arrays sorting object


【解决方案1】:

事实上,您不需要对数组进行排序,但您想重新创建它。

你应该使用以下函数:

function changeArrayOrder($categories) {
    $categories = array_values($categories);
    return array (
        $categories[2],
        $categories[0],
        $categories[1],
    );
}

并使用以下命令运行它:

$categories = changeArrayOrder($categories);

现在如果你运行你的循环,你会得到结果:

test, hello, world, 

【讨论】:

    猜你喜欢
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 2013-02-09
    • 2021-11-01
    • 2020-01-14
    相关资源
    最近更新 更多