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

59 views Asked by At

I'm trying to call methods while building an array. I am building a fairly large config array which contains many re usable blocks.

This is the array that I'd like to get:

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

This is how I'd 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 this gives me

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

There are 2 answers

0
giaour On BEST ANSWER

Instead of constructing the "masterKey" field as a literal, merge the arrays returned by self::getValueField:

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

Just want to add that, for @giaour answer to work, code for the getValueField function should be:

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