天天看點

php Yii2.0 ArrayHelper::map() 用法剖析

從多元數組或數組中建構一個映射(鍵-值 的形式)

通過“

$from

”和“

$to

”參數指定對應的鍵值或屬性名稱來設定的映射關系。

當然也可以根據分組字段“

$group

”來進一步分組的映射。

舉個例子:

$array = [
          ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
          ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
          ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
      ];
           

上面的數組執行以下方法

$result = ArrayHelper::map($array, 'id', 'name');
           

得到的結果是

[
    '123' => 'aaa',
    '124' => 'bbb',
    '345' => 'ccc',
]
           

還可以添加第四個參數

$result = ArrayHelper::map($array, 'id', 'name', 'class');
           

得到的結果是

[
    'x' => [
        '123' => 'aaa',
        '124' => 'bbb',
    ],
    'y' => [
        '345' => 'ccc',
    ],
]
           

下面是map方法的詳細代碼

/**
  * @paramarray $array
 * @param string|Closure $from
 * @param string|Closure $to
 * @param string|Closure $group
 * @return array
 */
public static function map($array, $from, $to, $group = null)
{
    $result = [];
    foreach ($array as $element) {
        $key = static:: getValue($element, $from);
        $value = static:: getValue($element, $to);
        if ($group !== null) {
            $result[ static:: getValue($element, $group)][$key] = $value;
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}
           

文章轉載自 http://u.cxyblog.com/10/article-aid-329.html