Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 用于对对象数组进行排序的递归函数_Php_Arrays_Sorting_Recursion - Fatal编程技术网

Php 用于对对象数组进行排序的递归函数

Php 用于对对象数组进行排序的递归函数,php,arrays,sorting,recursion,Php,Arrays,Sorting,Recursion,我一直在尝试编写一个递归函数,该函数将根据另一个数组(简单的数字数组)提供的顺序对对象数组重新排序 我想使用此排序函数通过“模板”数组对对象数组进行排序,该数组只包含数组中每个对象的一个属性进行排序,例如 $template=['A','B','C'] 要排序的数组: $myArray = [ new Element('B'), new Element('C'), new Element('A'), ] class Element { public $name;

我一直在尝试编写一个递归函数,该函数将根据另一个数组(简单的数字数组)提供的顺序对对象数组重新排序

我想使用此排序函数通过“模板”数组对对象数组进行排序,该数组只包含数组中每个对象的一个属性进行排序,例如

$template=['A','B','C']

要排序的数组:

$myArray = [
    new Element('B'),
    new Element('C'),
    new Element('A'),
]

class Element
{
    public $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

我没有成功。也许您对如何处理此任务有一些想法?

我不知道递归如何帮助您完成此任务。以下是如何使用内置排序功能:

usort($myArray, function(Element $a, Element $b) use ($template) {
    return array_search($a->name, $template) - array_search($b->name, $template);
});
  • usort
    根据给定的比较回调进行排序
  • 我在回调中添加了
    元素
    类型提示,因为排序函数只能处理
    元素
    对象的数组
  • array\u search
    返回
    $template
    数组中给定的
    名称
    属性值的键。如果该值在数组中不存在,它将被放置在开头,因为结果
    false
    被强制为
    0

我还设法使用递归进行排序-如下所示:

function orderRecursively($template, $myArray, &$ordered)
{
    foreach($myArray as $k => $v) {
        if ($myArray[$k]->name == $template[0]) {
            $ordered[] = $myArray[$k];
            array_splice($template, 0, 1);
        }
    }
    if (!empty($template)) orderRecursively($template, $myArray, $ordered);
}

$ordered = [];
order($template, $myArray, $ordered);
$ordered
将保存已排序的对象数组。
尽管如此,我还是觉得@fschmengler的答案更加优雅。

看看这里:我认为这与您的问题类似。它必须是一个递归函数,为什么您不能使用PHP的任何排序函数呢?@georaldc,是的,我想调整此函数,以便根据模板数组对对象数组进行排序,其中模板数组将仅保存数组中存储的对象的一个属性进行排序。我会修改我的问题,让它更清楚。这是一个很好的、简洁的方法。实际上,没有特别的理由说明它必须是一个递归函数。