51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

PHP一个数组按另一个数组顺序排序

PHP实现将一个数组按另一个数组顺序进行排序,PHP根据一个数组对另一个数组进行排序
顺序约束数据(20条):
$sort_list = array(20) {
  [0] => int(30702)
  [1] => int(30373)
  [2] => int(32110)
  [3] => int(32207)
  [4] => int(31923)
  [5] => int(1497)
  [6] => int(32003)
  [7] => int(30397)
  [8] => int(32086)
  [9] => int(31920)
  [10] => int(30795)
  [11] => int(31928)
  [12] => int(32071)
  [13] => int(32456)
  [14] => int(31224)
  [15] => int(32219)
  [16] => int(32726)
  [17] => int(31508)
  [18] => int(32381)
  [19] => int(41212)
}
待排序数据(5条):
$data = array(5) {
  [1497] => array(3) {
    ["houseid"] => int(1497)
    ["price"] => int(25000)
    ["area"] => array(2) {
      ["min"] => int(81)
      ["max"] => int(193)
    }
  }
  [30373] => array(3) {
    ["houseid"] => int(30373)
    ["price"] => int(18000)
    ["area"] => array(2) {
      ["min"] => int(109)
      ["max"] => int(189)
    }
  }
  [30397] => array(3) {
    ["houseid"] => int(30397)
    ["price"] => int(12000)
    ["area"] => array(2) {
      ["min"] => int(90)
      ["max"] => int(132)
    }
  }
  [30702] => array(3) {
    ["houseid"] => int(30702)
    ["price"] => int(19188)
    ["area"] => array(2) {
      ["min"] => int(0)
      ["max"] => int(188)
    }
  }
  [31224] => array(3) {
    ["houseid"] => int(31224)
    ["price"] => int(15149)
    ["area"] => array(2) {
      ["min"] => int(64)
      ["max"] => int(178)
    }
  }
}
思路:

1、获取两者的交集:

$sort_reference = array_intersect_key(array_flip($sort_list),$data);
var_dump($sort_reference);
结果:
array(5) {
  [30702] => int(0)
  [30373] => int(1)
  [1497] => int(5)
  [30397] => int(7)
  [31224] => int(14)
}
函数说明:
array_flip() 函数用于反转/交换数组中所有的键名以及它们关联的键值。
array_intersect_key() 函数用于比较两个(或更多个)数组的键名 ,并返回交集。

2、参考交集的数组顺序进行排序

$new_list = array_replace($sort_reference,$data)
var_dump($new_list);
结果:
array(5) {
  [30702] => array(3) {
    ["houseid"] => int(30702)
    ["price"] => int(19188)
    ["area"] => array(2) {
      ["min"] => int(0)
      ["max"] => int(188)
    }
  }
  [30373] => array(3) {
    ["houseid"] => int(30373)
    ["price"] => int(18000)
    ["area"] => array(2) {
      ["min"] => int(109)
      ["max"] => int(189)
    }
  }
  [1497] => array(3) {
    ["houseid"] => int(1497)
    ["price"] => int(25000)
    ["area"] => array(2) {
      ["min"] => int(81)
      ["max"] => int(193)
    }
  }
  [30397] => array(3) {
    ["houseid"] => int(30397)
    ["price"] => int(12000)
    ["area"] => array(2) {
      ["min"] => int(90)
      ["max"] => int(132)
    }
  }
  [31224] => array(3) {
    ["houseid"] => int(31224)
    ["price"] => int(15149)
    ["area"] => array(2) {
      ["min"] => int(64)
      ["max"] => int(178)
    }
  }
}
函数说明:
array_replace() 函数使用后面数组的值替换第一个数组的值。

3、考虑json前端数据顺序(key值大小混乱),重新生成升序key值顺序

$new_list = array_merge(new_list)
赞(0)
未经允许不得转载:工具盒子 » PHP一个数组按另一个数组顺序排序