• 234

php对二维数组排序

排序前
$arr = array(
  'apple' => array('weight'=>'3'),
  'orange' => array('weight'=>'5'),
  'banana' => array('weight'=>'2'),
  'tomato' => array('weight'=>'1'),
);
排序后(根据weight排序)
?

请教大家php怎么写

阅读 277
评论
    3 个回答
    $arr = [
        ['name' => 'apple', 'weight' => '3'],
        ['name' => 'orange', 'weight' => '5'],
        ['name' => 'banana', 'weight' => '2'],
        ['name' => 'tomato', 'weight' => '1'],
    ];
    
    usort($arr, function ($current, $next): int {
        return $current['weight'] > $next['weight'] ? 1 : -1;
    });
    
    var_dump($arr);

      /**

      • @desc arraySort php二维数组排序 按照指定的key 对数组进行自然排序
      • @param array $arr 将要排序的数组
      • @param string $keys 指定排序的key
      • @param string $type 排序类型 asc | desc
      • @return array

      */
      function arraySort($arr, $keys, $type = 'asc')
      {

      $keysvalue = $new_array = array();
      foreach ($arr as $k => $v) {
          $keysvalue[$k] = $v[$keys];
      }
      if ($type == 'asc') {
          natsort($keysvalue);
      }
      if ($type == 'desc') {
          natsort($keysvalue);
          // 将原数组中的元素顺序翻转,如果第二个参数指定为 true,则元素的键名保持不变
          $keysvalue = array_reverse($keysvalue, TRUE);
      }
      foreach ($keysvalue as $k => $v) {
          $new_array[$k] = $arr[$k];
      }
      return $new_array;

      }
      $arr = arraySort($arr, "weight", "asc" );
      var_dump($arr);

        • 40
        $arr = array(
          'apple' => array('weight'=>'3'),
          'orange' => array('weight'=>'5'),
          'banana' => array('weight'=>'2'),
          'tomato' => array('weight'=>'1'),
        );
        $weight = array_column($arr, 'weight');
        array_multisort($weight, SORT_ASC, $arr);
        var_dump($arr);
          撰写回答

          登录后参与交流、获取后续更新提醒