PHP - Inserting into an array by calling a method that returns both key and value

I am trying to call methods when constructing an array. I am creating a fairly large config array that contains many reusable blocks.

This is the array I would like to receive:

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

      

This is how I would like to generate it:

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

      

But it gives me

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

      

+3


source to share


2 answers


Instead of constructing the field "masterKey"

as a literal, concatenate the arrays returned self::getValueField

:



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

      

+3


source


Just want to add that for @ giaour's answer to work, the code for the function getValueField

should be:



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

      

0


source







All Articles