PHP - 通过调用返回键和值的方法插入数组

时间:2015-06-12 22:46:41

标签: php arrays associative-array

我试图在构建数组时调用方法。我正在构建一个相当大的配置数组,其中包含许多可用的块。

这是我想要的数组:

array(
   "masterKey" => array(
      "myKey" => array(
         "valueField" => "hi"
      ),
      "anotherKey" => array(
         "valueField" => "hi again"
      )
      ....
   )
);

这就是我想要生成它的方式:

array(
   "masterKey" => array(
      self::getValueField("myKey", "hi"),
      self::getValueField("anotherKey", "hi again"),
      ...
   )
);
private static function getValueField($key, $value)
{
   return array($key => 
      "valueField" => $value
   );
}

但是这给了我

array(
   "masterKey" => array(
      [0] => array(
         "myKey" => array(
            "valueField" => "hi"
         )
      ),
      [1] => array(
         "anotherKey" => array(
           "valueField => "hi again"
         )
      )
   )
);

2 个答案:

答案 0 :(得分:3)

不是将"masterKey"字段构造为文字,而是合并self::getValueField返回的数组:

array(
   "masterKey" => array_merge(
       self::getValueField("myKey", "hi"),
       self::getValueField("anotherKey", "hi again"),
       ...
    )
);

答案 1 :(得分:0)

只想补充一点,对于@giaour的工作答案,getValueField函数的代码应为:

<?php
private static function getValueField($key, $value)
{
    return array(
        $key => array(
            "valueField" => $value
        )
    );
}