基于另一个数组索引

时间:2017-06-14 12:47:23

标签: php sorting

我有两个数组

// array of objects
$records = array(
  [0] => (object) [
             'id' => 1, //  (*)
             ....
        ],
  [1] => (object) [
            'id' => 2, //  (*)
             ....
        ],
   [2] => (object) [
            'id' => 3, //  (*)
             ....
        ],
);

// array 2
// the keys in this array refer to the object ids (*)
$sorted = array(
    '2'  => 7,
    '3'  => 4,
    '1'  => 2,
);

$new_records = array();

我想要做的是根据第二个数组的键索引的顺序对第一个数组(即对象)的值进行排序,因此在这种情况下的最终结果将变为:

 $new_records = array(
      [0] => (object) [
                 'id' => 2,
                 ....
            ],
      [1] => (object) [
                'id' => 3,
                 ....
            ],
       [2] => (object) [
                'id' => 1,
                 ....
            ],
    );

$records = $new_records;

4 个答案:

答案 0 :(得分:0)

代码:(Demo

$records = [(object)['id' => 1], (object)['id' => 2], (object)['id' => 3]];
$sorted = ['2' => 7, '3' => 4, '1' => 2];

$tempArr = array();
foreach ($records as $value) {
     $tempArr[$value->id] = $value;
}
$resultArr = array_values(array_replace($sorted, $tempArr));

var_export($resultArr);

输出:

array (
  0 => 
  stdClass::__set_state(array(
     'id' => 2,
  )),
  1 => 
  stdClass::__set_state(array(
     'id' => 3,
  )),
  2 => 
  stdClass::__set_state(array(
     'id' => 1,
  )),
)

答案 1 :(得分:0)

试试这个

$new_records = array();
foreach( $sort as $id => $pos ) {
    foreach( $records as $record ) {
        if( $record[ 'id' ] == $id ) {
            $new_records[] = $record;
            break;
        }
    }
}

答案 2 :(得分:0)

这使得工作成功     

$records = array(
   0 => (object) [
             'id' => 1, //  (*)
        ],
   1 => (object) [
            'id' => 2, //  (*)
        ],
   2 => (object) [
            'id' => 3, //  (*)
        ],
);

// array 2
// the keys in this array refer to the object ids (*)
$sorted = array(
    '2'  => 7,
    '3'  => 4,
    '1'  => 2,
);

$keySorted = array_keys($sorted);

usort($records, function ($a, $b) use ($keySorted) {

    $pos_a = array_search($a->id, $keySorted);
    $pos_b = array_search($b->id, $keySorted);
    return $pos_a - $pos_b;
});

var_dump($records);

答案 3 :(得分:0)

在这里,我创建了数组排序,并使用 current()添加到对象数组中, key()来自php。

$i = 0;
while ($value = current($sorted)) {

    $key = key($sorted); // get key from array 2
    $records[i]->array('id' => $key); // set key to array of object

    next($array);
    $i++;
}

我希望这对你有所帮助。