比较&对另一个数组排序对象数组

时间:2016-12-12 10:39:52

标签: php arrays sorting

我目前有一个对象数组,如下所示:

$aa = new StdClass;
$aa->name = 'aa';
$aa->index = 30;
$bb = new StdClass;
$bb->name = 'bb';
$bb->index = 30;
$cc = new StdClass;
$cc->name = 'cc';
$cc->index = 10;
$dd = new StdClass;
$dd->name = 'dd';
$dd->index = 20;
$ee = new StdClass;
$ee->name = 'ee';
$ee->index = 10;

我已将对象放入数组中进行排序:

$arr = [$aa, $bb, $cc, $dd];

我还有一个额外的数组,我想用它来按顺序排序对象,例如$aa->index

$map = [30, 20, 10, 10, 30];

预期结果将是:

[$aa, $dd, $cc, $ee, $bb]

$aa$bb中的另一个未定义,它们必须完全不重复,并且必须在某处指定所有索引。

$arr 使用$map循环设置的顺序排列foreach()的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

老实说,我不确定我是否理解这个问题,但这是对你的问题的尝试:

$aa = new stdClass;
$aa->name = 'aa';
$aa->index = 30;
$bb = new stdClass;
$bb->name = 'bb';
$bb->index = 30;
$cc = new stdClass;
$cc->name = 'cc';
$cc->index = 10;
$dd = new stdClass;
$dd->name = 'dd';
$dd->index = 20;
$ee = new stdClass;
$ee->name = 'ee';
$ee->index = 10;


$arr = [$aa, $bb, $dd, $cc,  $ee];
$map = [30, 30 , 10,  20];

function sort_ish($arr, $map)
{
    $return = [];

    while($element = array_shift($map))
    {
        foreach($arr as $key => $value)
        {
            if($element == $value->index)
            {
                $return[] = $value;
                unset($arr[$key]);
                break 1;
            }
        }
    }

    return $return;
}

print_r(sort_ish($arr, $map));

将输出:

Array
(
    [0] => stdClass Object
(
    [name] => aa
[index] => 30
        )

    [1] => stdClass Object
(
    [name] => bb
[index] => 30
        )

    [2] => stdClass Object
(
    [name] => cc
[index] => 10
        )

    [3] => stdClass Object
(
    [name] => dd
[index] => 20
        )

)

真的,我不得不使用foreach。

另一方面,我对这个问题很开心,即使我没有把它弄好。谢谢OP。

答案 1 :(得分:0)

我在技术上没有调用foreach()循环,但是我使用递归函数进行循环。您需要做的就是将对象数组($arr)作为第一个参数传递,将数组映射($mapArr)作为第二个函数 mrSorty() 。然后,mrSorty()将从此处通过array_search()ksort()等神奇函数传递对象数组。

$arr = [$aa, $bb, $cc, $dd, $ee];
$mapArr = [30, 20, 10, 10, 30];

function mrSorty($arr, $mapArr, $objCount=0) {

    static $newArr; 

      if ((count($mapArr)) > 0 && $objCount < ($objCount+count($mapArr)) ) {

            $obj = $arr[$objCount];
            $key = array_search($obj->index, $mapArr);
            $newArr[$key] = $obj;
            unset($mapArr[$key]);
            mrSorty($arr, $mapArr, ++$objCount);
      } 

      ksort($newArr); //Sort the Array by Key
      return $newArr; 
}



$arrayReturn = mrSorty($arr, $mapArr); //Array of Objects & Array Map

var_dump($arrayReturn);

<强>输出

array(5) {
[0] => object(stdClass) #1 (2) { ["name"]= > string(2)"aa" ["index"] => int(30)}
[1] => object(stdClass) #4 (2) { ["name"]= > string(2) "dd" ["index"] => int(20)}
[2] => object(stdClass) #3 (2) { ["name"]= > string(2) "cc" ["index"] => int(10)}
[3] => object(stdClass) #5 (2) { ["name"]= > string(2) "ee" ["index"] => int(10)}
[4] => object(stdClass) #2 (2) { ["name"]= > string(2)"bb" ["index"] => int(30)}
}

编辑:

严肃地说,如果你需要我详细说明,请告诉我。