Reputation: 616
I would like to make associative array using foreach to use in Yii 2 dropdownlist. My goal is to make array like following using foreach-
$array= [
['id' => '123', 'name' => 'abc'],
['id' => '124', 'name' => 'def'],
];
And then I want to use them using Yii 2 ArrayHelper::map().
$result = ArrayHelper::map($array, 'id', 'name');
How do I make the array using foreach?
Upvotes: 1
Views: 15334
Reputation: 33538
Yii way to build items for drop-down list is exactly as you described, using ArrayHelper::map()
:
$items = ArrayHelper::map($array, 'id', 'name');
You don't need to use foreach
here, just pass results of ActiveQuery
as array:
$array = YourModel::find()->all();
Update:
Thanks. But here, I am actually calculating custom value for 'name' and for that reason I want to use foreach to generate the array after the calculation
You definetely need to add this information to the question, but anyway, you can use the ArrayHelper
for that too. Take a look at toArray
method. It can be used for both object / array of objects. After processing with this method you can use map
.
Official docs:
Upvotes: 2