【问题标题】:Push variable to array using name as key?使用名称作为键将变量推送到数组?
【发布时间】:2012-09-11 19:33:29
【问题描述】:

我有以下变量:

$something = 'whatever';
$hello = array();
$test = 123;

我想将它们推送到这样的数组中:

$data['something'] = 'whatever';
$data['hello'] = array();
$data['test'] = 123;

我想知道是否有某种 PHP 函数(类似于 array_push())可以使用变量名作为键值将变量推送到数组中?

【问题讨论】:

    标签: php


    【解决方案1】:

    是的,有。 compact() 会做到这一点。

    【讨论】:

    • 是的,正是我想要的。是否可以附加到现有数组或必须创建一个新数组?
    • 该函数返回一个数组,但你可以使用array_merge将它与另一个数组结合起来。
    • 没有办法把它和类成员变量一起使用,比如$something->whatever,对吧?
    • @Jakobud,没想到,它不允许您指定上下文。
    猜你喜欢
    • 1970-01-01
    • 2015-11-06
    • 2012-05-09
    • 2023-03-27
    • 2011-12-30
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    相关资源
    最近更新 更多