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条回答 默认 最新

  • duanbiao4025 2015-09-11 15:28
    关注

    The function is just easier to type - you do not have to make so many brackets and quotation mark. It makes things easier.

    For performance: If you set the array values with normal syntax, it is faster, because you do not have to explode the path or check for existence before. But this takes not so many time.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集