2

This is my code.

$activities = ArrayHelper::map(LibActivity ::find()->all(), 'id', 'activity_name');

it generates the following.

    <select id="tblncddpvlcccbis-activity_id" class="form-control" name="TblNcddpVlccCbis[activity_id]">
    <option value="">---Select Type of Activity---</option>
    <option value="1">Social Mobilization</option>
    <option value="2">Project Identification/Selection</option>
    <option value="3">Project Approval</option>
    </select>

What I want is to concatenate the third parameter so that the option would be the id-activity_name like this:

$activities = ArrayHelper::map(LibActivity ::find()->all(), 'id', 'id'.'-'.'activity_name');

<select id="tblncddpvlcccbis-activity_id" class="form-control" name="TblNcddpVlccCbis[activity_id]">
<option value="">---Select Type of Activity---</option>
<option value="1">1-Social Mobilization</option>
<option value="2">2-Project Identification/Selection</option>
<option value="3">3-Project Approval</option>
</select>
1

2 Answers 2

4

I don't know if this is the standard way in YII or not but you can try it like this:

$libs = LibActivity ::find()->all();
foreach($libs as &$lib){
    $lib->activity_name = $lib->id.'-'.$lib->activity_name;
}

$activities = ArrayHelper::map($libs, 'id', 'activity_name');
// Todo With activities
Sign up to request clarification or add additional context in comments.

Comments

3

PHP has array_walk function that allows to apply a function to every item in the array.

So, here's how you do it:

$activities = ArrayHelper::map(LibActivity::find()->all(), 'id', 'activity_name');
array_walk($activities, function(&$value, $key){
    $value = $key.' '.$value;
});

In this case we pass an anonymous function that does exactly what you need. I think it's better to apply these changes to the resulting array, not to the original result set.

You can also optimize your original query. Assuming id and activity_name are actual table fields, you can do this:

LibActivity::find()->select(['id', 'activity_name'])->asArray()->all()

This way you'll only get the necessary fields and also avoid creating objects where you don't need them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.