doudou8783
2015-09-11 15:05
浏览 43
已采纳

在PHP中为数组添加值的最快方法是什么

I'm working on a project that has an Arr helper class and I am curious about something: Is there a benefit in doing this:

/**
 * Sets an array value
 *
 * @param array  $array
 * @param string $path
 * @param mixed  $value
 *
 * @return void
 */
public static function set(array &$array, $path, $value)
{
    $segments = explode('.', $path);
    while (count($segments) > 1) {
        $segment = array_shift($segments);
        if ( ! isset( $array[$segment] ) || ! is_array($array[$segment])) {
            $array[$segment] = [];
        }
        $array =& $array[$segment];
    }
    $array[array_shift($segments)] = $value;
}

Arr::set($data['stories'], 'fields.age', '3');

Over this:

$data['stories']['fields']['age'] = '3';

Or is there a better, faster way?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题