我有一系列哈希,
[
{id: 1, tool_id: 1, user_ids: [1]},
{id: 2, tool_id: 2, user_id: [2]},
]
我想搜索它,如果有某个tool_id,我想将user_id附加到user_ids列表。
答案 0 :(得分:1)
说user_id
100
tool_id = 1
为arr.each { |a| a[:user_ids] << 100 if a[:tool_id] == 1 }
#=> [{:id=>1, :tool_id=>1, :user_ids=>[1, 100]}, {:id=>2, :tool_id=>2, :user_id=>[2]}]
:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$model->start_date = strtotime($model->start_date);
$model->start_date = date('Y-m-d',$model->start_date);
$model->end_date = strtotime($model->end_date);
$model->end_date = date('Y-m-d',$model->end_date);
$model->date_of_request = strtotime($model->date_of_request);
$model->date_of_request = date('Y-m-d',$model->date_of_request);
//$model->start_date = date_format($model->start_date,'Y-m-d');
if($model->save()){
return $this->redirect(['view', 'id' => $model->id]);
}else{
return $this->render('create', [
'model' => $model,
]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
//new line
答案 1 :(得分:1)
鉴于
h = [
{id: 1, tool_id: 1, user_ids: [1]},
{id: 2, tool_id: 2, user_id: [2]},
]
尝试
def add_user_id(h, tid, uid)
el = h.find { |i| i[:tool_id] == tid }
el[:user_id] << uid if el
end
add_user_id(h, 2, 3)
p h
输出
[{:id =&gt; 1,:tool_id =&gt; 1,:user_ids =&gt; [1]},{:id =&gt; 2,:tool_id =&gt; 2,:user_id =&gt; [ 2,3]}]
答案 2 :(得分:1)
使用Enumerable#find()
的简短版本。 (没有处理未知tool_id
值。)
# add the user_id 4 to the hash with the tool_id 2
arr.find { |e| e[:tool_id] == 2 }[:user_ids] << 4