【问题标题】:PHP re-arrange array elements [duplicate]PHP重新排列数组元素[重复]
【发布时间】:2014-12-15 06:53:42
【问题描述】:

我有一个动态使用key 作为表头的数组,我想按此顺序重新排列以下内容:

fullname, age, email, tel, project, type, purpose, budget, income 

默认数组元素

Array
(
    [type] => Plastic
    [purpose] => Sell
    [budget] => 401,000-500,000
    [income] => 12,000-29,999
    [fullname] => John Smith
    [age] => 30
    [email] => john@email.com
    [tel] => 12345678
    [project] => Project A
)

可以通过move在代码中手动完成吗?

【问题讨论】:

  • 你需要它来使用循环,排序只能按照A-Z - 0-9 asc, desc 的顺序。对于自定义订单循环是要走的路

标签: php arrays sorting


【解决方案1】:
$arr = array();// THIS IS YOUR INPUT ARRAY.
$sort = array('fullname', 'age', 'email', 'tel', 'project', 'type', 'purpose', 'budget', 'income');
$n = array();
foreach ($sort as $v) {
  $n[$v] = $arr[$v];
}
echo '<pre>';
print_r($n);
echo '</pre>';

注意:这是一个示例,您也可以在循环中应用它。

Working Example

【讨论】:

    【解决方案2】:

    请查看以下链接

    Sort an Array by keys based on another Array?

    用于使用另一个数组对数组重新排序

    function sortArrayByArray(Array $array, Array $orderArray) {
        $ordered = array();
        foreach($orderArray as $key) {
            if(array_key_exists($key,$array)) {
                $ordered[$key] = $array[$key];
                unset($array[$key]);
            }
        }
        return $ordered + $array;
    }
    

    在上面的链接中检查这个功能

    【讨论】:

      【解决方案3】:

      其中$original_data 是包含您在问题中概述的数组的变量,您可以使用此逻辑根据一组列名对其进行重新排序:

      $new_sort_order = array(
          'fullname',
          'age',
          'email',
          'tel',
          'project',
          'type',
          'purpose',
          'budget',
          'income',
      );
      
      $sorted_data = array();
      foreach ($new_sort_order as $column_title) {
          if(isset($original_data[$column_title])) {
              $sorted_data[$column_title] = $original_data[$column_title];
          }
      }
      
      var_export($sorted_data);
      

      【讨论】:

        【解决方案4】:

        将所需的键顺序放入一个数组中,并为该键数组中的每个项目,从旧数组中放置其各自的内容。最后,新数组将按照 $arr 中提到的顺序排列。

        //$oldArr
        Array 
            (
                [type] => Plastic
                [purpose] => Sell
                [budget] => 401,000-500,000
                [income] => 12,000-29,999
                [fullname] => John Smith
                [age] => 30
                [email] => john@email.com
                [tel] => 12345678
                [project] => Project A
            )
        

        $oldArr 包含上面提到的 key => value 数组

        $arr = array('fullname','age','email','tel','project','type','purpose','budget','income');
        foreach($arr as $a)
        {
           if($oldArr[$a])
            $newArr[$a] = $oldArr[$a];
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-17
          • 2016-07-26
          相关资源
          最近更新 更多