【问题标题】:How can I sort an object in symfony?如何在 symfony 中对对象进行排序?
【发布时间】:2019-01-02 15:51:31
【问题描述】:

这是“字段”

{#751 ▼
  +"id": array:9 [▼
    "fieldName" => "id"
    "type" => "integer"
    "scale" => 0
    "length" => null
    "unique" => true
    "nullable" => false
    "precision" => 0
    "id" => true
    "columnName" => "id"
  ]
  +"username": array:8 [▼
    "fieldName" => "username"
    "type" => "string"
    "scale" => 0
    "length" => 25
    "unique" => true
    "nullable" => false
    "precision" => 0
    "columnName" => "username"
  ]
  +"unique_id": array:8 [▼
    "fieldName" => "unique_id"
    "type" => "string"
    "scale" => 0
    "length" => 10
    "unique" => true
    "nullable" => false
    "precision" => 0
    "columnName" => "unique_id"
  ]
  +"password": array:8 [▼
    "fieldName" => "password"
    "type" => "string"
    "scale" => 0
    "length" => 64
    "unique" => false
    "nullable" => false
    "precision" => 0
    "columnName" => "password"
  ]
  +"email": array:8 [▼
    "fieldName" => "email"
    "type" => "string"
    "scale" => 0
    "length" => 191
    "unique" => true
    "nullable" => false
    "precision" => 0
    "columnName" => "email"
  ]
  +"isActive": array:8 [▼
    "fieldName" => "isActive"
    "type" => "boolean"
    "scale" => 0
    "length" => null
    "unique" => false
    "nullable" => false
    "precision" => 0
    "columnName" => "is_active"
  ]
}

我希望用户名总是在开头,密码总是在结尾。

这是我的方法:

  usort($fields, function ($a, $b) {  if ($a['fieldName'] == 'username' || $b['fieldName'] == 'password') return -1;
        elseif ($a['fieldName'] == 'password' || $b['fieldName'] == 'username') return 1;
        else return 0;
      });

但我收到一条错误消息:

警告:usort() 期望参数 1 是数组,给定对象

【问题讨论】:

  • @Thefourthbird 这给出了错误Cannot pass parameter 1 by reference
  • 然后先将其转换为数组$fields = (array)$fields; usort($fields
  • 或者您可以使用$fields = json_decode(json_encode($fields), true); 以不同的方式转换为数组

标签: php arrays symfony oop usort


【解决方案1】:

usort的第一个参数应该是一个数组,$fields是一个对象。一种选择是将其转换为如下数组:

$fields = (array)$fields;

然后传给usort:

usort($fields, function ($a, $b) {
    if ($a['fieldName'] == 'username' || $b['fieldName'] == 'password') return -1;
    elseif ($a['fieldName'] == 'password' || $b['fieldName'] == 'username') return 1;
    else return 0;
});

【讨论】:

    猜你喜欢
    • 2015-04-11
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    相关资源
    最近更新 更多