Search code examples
phpyiiyii2

Yii2- ArrayHelper change index of array


I have an array as follows:

[
    0 => [
        'name' => 'CARD'
        'id' => '0'
    ]
    1 => [
        'name' => 'MOBILE'
        'id' => '1'
    ]
    2 => [
        'name' => 'GIFT'
        'id' => '2'
    ]
]

I want to change the key id to type in all the array. Is there a way to do this in Yii2 using ArrayHelper?


Solution

  • You can use getColumn() for this:

    $result = ArrayHelper::getColumn($array, function ($data) {
        return [
            'name' => $data['name'],
            'type' => $data['id'],
        ];
    });
    

    But it will not really differ from array_map() or simple foreach.