/** *二维数组变维位数组 * $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'); * // the result is: * // [ * // '123' => 'aaa', * // '124' => 'bbb', * // '345' => 'ccc', * // ] * * $result = ArrayHelper::map($array, 'id', 'name', 'class'); * // the result is: * // [ * // 'x' => [ * // '123' => 'aaa', * // '124' => 'bbb', * // ], * // 'y' => [ * // '345' => 'ccc', * // ], * // ] * ``` * * @param array $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; }
二维数组变维位数组或格式化二维数组
最新推荐文章于 2022-03-13 22:39:22 发布