M
M
Michael2018-11-18 21:33:15
Yii
Michael, 2018-11-18 21:33:15

YII2 array output in yii2-widget-select2?

Hello everybody! Tell me how to get an array and display it in yii2-widget-select2 ? At the moment I am getting an array like this:

$equipment = Type::find()->indexBy('id')->asArray()->all();
$result = ArrayHelper::map($equipment, 'id', 'name', 'parent_id');

But this method does not suit the fact that the category in the drop-down list is displayed as an id, but it is necessary that the category be displayed with a name. The question is how to write a function for getting an array, where instead of a category id there will be its name?
5bf1ad56339a7572700692.png5bf1b0056ee7c476350643.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Arman, 2018-11-18
@Bally

you can try to bypass it somehow

$equipment = Type::find()->indexBy('id')->asArray()->all();
$equipment = array_map(function ($row) use ($equipment) {
    $row['parent_name'] = isset($equipment[$row['parent_id']]) ? $equipment[$row['parent_id']]['name'] : null;
    return $row;
}, $equipment);
$equipment = array_filter($equipment, function ($row) {
    return $row['parent_name'];
});
$result = ArrayHelper::map($equipment, 'id', 'name', 'parent_name');

up:
or better try
$equipment = Type::find()->indexBy('id')->asArray()->all();
$equipment = array_map(function ($row) use ($equipment) {
    $row['parent_name'] = isset($equipment[$row['parent_id']]) ? $equipment[$row['parent_id']]['name'] : $row['parent_id'];
    return $row;
}, $equipment);
$result = ArrayHelper::map($equipment, 'id', 'name', 'parent_name');
if(isset($result[0])) {
    unset($result[0]);
}

M
Michael, 2018-11-18
@Bally

Thank you! Your version of the code is ideal for solving the problem! After applying the code, there is only one question left, now all categories are displayed in the select, including that the parent categories are displayed in a separate category "0". Can you tell me how to remove them so that they are not displayed as a separate array "0", but at the same time they do not disappear as subheadings of device categories?
5bf1be8aeee98839280765.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question