对数组键进行排序,其中键与内部数组的值匹配

时间:2014-03-07 09:30:01

标签: php arrays sorting

我正在尝试对一组数组进行排序,其中外部数组的键与内部数组的值匹配' id_rel'。

示例数组:

array = (
  [5] => array (
      ['content'] => 'some text',
      [id_rel] => 88
  ),
  [49] => array (
      ['content'] => 'some text',
      [id_rel] => NULL
  ),
  [88] => array (
      ['content'] => 'some text',
      [id_rel] => 5
  ),
  [3] => array (
      ['content'] => 'some text',
      [id_rel] => NULL
  )
)

在此示例中,项目[5]具有“id_rel”#39; ' 88',表示数组中的项目[88]。我想将这两个项目彼此相邻。

排序后它应该是这样的(注意,键应保持不变):

array = (
  [5] => array (
      ['content'] => 'some text',
      [id_rel] => 88
  ),
  [88] => array (
      ['content'] => 'some text',
      [id_rel] => 5
  ),
  [49] => array (
      ['content'] => 'some text',
      [id_rel] => NULL
  ),
  [3] => array (
      ['content'] => 'some text',
      [id_rel] => NULL
  )
)

实现这样排序的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

这样的事可能有用:

$newArray = array();
ksort($array);
foreach ($array as $key => $val) {
    // Add it to the new array
    $newArray[$key] = $val;
    // Remove it
    unset($array[$key]);

    // If no id_rel, move on
    if (empty($val['id_rel'])) {
        continue;
    }

    // Get id_rel's
    foreach ($array as $subKey => $subVal) {
        if ($subKey == $val['id_rel']) {
            $newArray[$subKey] = $subVal;
            unset($array[$subKey]);
        }
    }
}
unset($array, $subKey, $subVal, $key, $val);
var_dump($newArray);

演示:https://ideone.com/SVRq5g

答案 1 :(得分:0)

相当丑陋的方式,但您可以创建自定义排序:

$arr = array(
  5 => array (
      'id' => 5,
      'content' => 'some text',
      'id_rel' => 88
  ),
  49 => array (
        'id' => 49,
      'content'=> 'some text',
      'id_rel' => NULL
  ),
  88 => array (
        'id' => 88,
      'content' => 'some text',
      'id_rel' => 5
  ),
  3 => array (
        'id' => 3,
      'content' => 'some text',
      'id_rel' => NULL
  )
);
uasort($arr,function($a, $b){
    if(empty($a['id_rel']) && !empty($b['id_rel'])){
        return 1;
    }elseif(empty($b['id_rel']) && !empty($a['id_rel'])){
        return -1;
    }
    if($a['id_rel'] == $b['id'] || $a['id'] == $b['id_rel']){
        return 0;
    }else{
        return $b['id']-$a['id'];
    }
});
print_r($arr);

请注意,此数组包含'id'字段,否则uasort无法访问id