Search code examples
phparraysyii2array-map

In Yii2 how to use array index as $key when using ArrayHelper::map() method?


$lang = [
   'en' => ['id'=>'1', 'name' => 'English', 'short' => '1', 'active' => '1',],
   'tn' => ['id'=>'2', 'name' => 'Tamil', 'short' => '2', 'active' =>'1',],
]; // sample array`    

In yii2 i can use the array map method as follow. ArrayHelper::map($lang,'id','name');

But how to put the array index ('en' and 'tn') in the place 'id' ex:ArrayHelper::map($lang, array_index,'name');

thanks


Solution

  • This is not a function of ArrayHelper as far as i know, but can't you just make your own? Give something like this a shot:

    function YourArrayHelper($arr)
    {
        $returnArr = [];
        foreach($arr as $key => $value)
        {
            $returnArr[$key] = $value['name'];
        }
        return $returnArr;
    }
    
    $types = [
        'en' => ['id'=>'1', 'name' => 'Sell', 'short' => '1', 'active' => '1',],
        'tn' => ['id'=>'2', 'name' => 'buy','short' => '2', 'active' =>'1',],
    ]; // sample array
    
    var_dump(ArrayHelper::map($types,'id','name'));
    echo '<br>';
    var_dump(YourArrayHelper($types));