2015-07-21 74 views
1

我想在Yii2 map()方法中使用PHP for loop來創建一個關聯數組。如何使用PHP for循環在Yii 2數組映射()中使用關聯數組?

陣列看起來像在波紋管格式 -

$listArray = [ 
    ['id' => '1', 'name' => 'Peter/5'], 
    ['id' => '2', 'name' => 'John/7'], 
    ['id' => '3', 'name' => 'Kamel/9'], 
]; 

ID和名稱將通過循環的每次迭代改變。在這裏,該名稱在循環內部進行一些計算後將始終保持自定義值。等作爲以下

$listData=ArrayHelper::map($listArray,'id','name'); 

使用Active記錄查找列表陣列後直接我可以使用地圖()方法,然後使用在地圖

最後,該列表將在地圖中使用()方法() 方法。但它並沒有給我使用自定義值的名稱屬性。

$listArray = UserList::find() 
     ->where(['status' => 1]) 
     ->orderBy('name') 
     ->all(); 

$listData=ArrayHelper::map($listArray,'id','name'); 

怎樣才能做到這一點?直接源代碼示例對我來說真的很棒。

在此先感謝。

+0

如果您可以遍歷返回的行,您可以輕鬆地爲每個循環構建一個關聯數組。我對Yii2不太熟悉,但我想象的原理是一樣的,你可以使用本地PHP來做到這一點。 –

+0

如果你請幫忙編寫代碼來創建對我來說真的很有幫助的關聯數組。我可以用()或{}編寫PHP泛型數組,但不能這樣使用[[],[]]。謝謝。 –

+0

@ xerxes333根據我所說的話回答如下。 –

回答

3

我假設你想查詢數據的ActiveRecord然後將數據傳輸到一個簡單的數組。

$listData = []; 

$listArray = UserList::find() 
    ->where(['status' => 1]) 
    ->orderBy('name') 
    ->all(); 

foreach($listArray as $user){ 
    $customName = $user->name . $this->someCalculation(); 
    $listData[] = ["id" => $user->id, "name" => $customName]; 
} 

或者你可以使用ArrayHelper類是這樣的:

$listArray = UserList::find() 
    ->where(['status' => 1]) 
    ->orderBy('name') 
    ->all(); 

$listData = ArrayHelper::toArray($listArray , [ 
    'app\models\UserList' => [ 
     'id', 
     'name' => function ($listArray) { 
      return $listArray->word . strlen($listArray->word); // custom code here 
     }, 
    ], 
]); 
+0

它按預期工作!謝謝。 –

1

我認爲在UserList的模型定義自定義計算規則是這樣做的首選方式:

public function getCustomRuleForUser(){ 
    // Do what ever you want to do with your user name. 
    return $this->name.'Your custom rule for name'; 

} 

而且用作:

$userList = UserList::find()->all(); 
    $listData=ArrayHelper::map($userList,'id','customRuleForUser'); 

現在,您有用於$listData的用戶名列表的自定義規則。