将数据推入数组内部的数组

Pushing data into an array that's inside of an array

所以这可能以前有人问过,或者我可能只是以一种完全奇怪的方式使用数组。无论如何,我想要做的是有一个数组,比方说.. $replacements = array(); 这个数组包括 keys[=44= 的所有数据] 和 替换 。不知道如何描述它,但这就是这个想法的来源:click——现在,假设我有如上所述的这个数组,我试图在我的函数内部附加到数组,一个选项允许您将一个键限制为一组动态页面。这就是我想象中的数组的样子:

array() {
    ["key1"] => "result"
    ["key2"] => "result2"
    ["key3 etc"] => "result3 etc"
}

那将是一个没有指定任何页面限制的键数组,这就是我为页面限制键附加额外数组时想象的数组。

array() {
    ["key1"] => "result"
    ["key2"] => "result2"
    ["key3 etc"] => "result3 etc"
    "homepage" = array() {
        ["home_key1"] => "this is a key in the homepage only"
        ["two_page_restricted"] => "this is a replacement in two restricted pages only"
    },
    "newspage" = array() {
        ["two_page_restricted"] => "this is a replacement in two restricted pages only"
    }
}

我不确定到目前为止我所说的是否有任何意义,但我想你明白了。这就是我到目前为止所获得的基本密钥替换:

function addTranslation($key, $replacement, $restricted = null) {
    if($restricted == null)
        array_push($this->translations, $key, $replacement);
    //else 
        //array_push($this->translations, )
    }

最后,我想要完成的是,如果 $restricted 不是 null 然后追加从它到 $this->translations 而不会干扰其他键。提前感谢您的任何帮助。

编辑: 如果有帮助,这就是我使用函数的方式:

两个页面: $class->addTranslation("{key}", "this is a key", array("homepage", "newspage");

对于任何页面: $class->addTranslation("{key}", "this is a key");

编辑2: 澄清一下,这是 PHP 而不是 JavaScript。

您是否尝试从数组中获取结果,然后将其添加到新数组中。

会是这样的:

var result = firstarray.key1;

newarray.push(结果);

抱歉应该注意到美元符号

然后如果你想使用 PHP 从数组中拉出一个字段你想这样做

$结果->字段[字段名][字段数组];

Array_push($结果);

希望我理解正确

为了回答主要问题,一种处理在数组属性的根级别或同一数组的多个子级别同时推送数据的方法可能如下所示:

class EntryHandler
{
    private $entries;

    function addEntry($key, $value, array $subArrayKeys = null) 
    {
        if($subArrayKeys == null)
        {
            $this->entries[$key] = $value;
            return; // Skip the subArrayKeys handling
        }

        foreach($subArrayKeys as $subArrayKey)
        {
            // Initialize the sub array if it does not exist yet
            if(!array_key_exists($subArrayKey, $this->entries))
            {
                $this->entries[$subArrayKey] = [];
            }
            // Add the value
            $this->entries[$subArrayKey][$key] = $value;
        }
    }
}

话虽如此,您指定此追加操作不应 "interfere with other keys"。在那种情况下,您描述您期望的数组的方式根本行不通。 使用这样的结构,您将无法获得具有相同值的翻译键和受限页面名称。

我认为这里正确的方法是采用一致的结构,其中多维数组的每一层都包含相同类型的数据。考虑到您的用例,您可以引入一个 "default" 域,除了页面特定的翻译之外,您还可以将其用作翻译的基础。


这是从我的一个项目中摘取的一小部分 class,据我所知,我根据您的用例对其进行了调整。它按照您为字符串处理部分链接的 post 中的建议使用 strtr

class Translator
{
    const DEFAULT_DOMAIN = '_default'; // A string that you are forbidden to use as a page specific domain name
    const KEY_PREFIX = '{';
    const KEY_SUFFIX = '}';

    private $translations = [];    

    public function addTranslation($key, $translation, array $domains = null)
    {
        // If no domain is specified, we add the translation to the default domain
        $domains = $domains == null ? [self::DEFAULT_DOMAIN] : $domains;
        foreach($domains as $domain)
        {
            // Initialize the sub array of the domain if it does not exist yet
            if(!array_key_exists($domain, $this->translations))
            {
                $this->translations[$domain] = [];
            }

            $this->translations[$domain][$key] = $translation;
        }
    }

    public function process($str, $domain = null)
    {
        return strtr($str, $this->getReplacePairs($domain));
    }

    private function getReplacePairs($domain = null)
    {
        // If the domain is null, we use the default one, if not we merge the default 
        // translations with the domain specific ones (the latter will override the default one) 
        $replaceArray = $domain == null 
            ? $this->translations[self::DEFAULT_DOMAIN] ?? [] 
            : array_merge($this->translations[self::DEFAULT_DOMAIN] ?? [], $this->translations[$domain] ?? []);

        // Then we add the prefix and suffix for each key
        $replacePairs = [];
        foreach($replaceArray as $baseKey => $translation)
        {
            $replacePairs[$this->generateTranslationKey($baseKey)] = $translation;
        }

        return $replacePairs;
    }

    private function generateTranslationKey($base)
    {
        return self::KEY_PREFIX . $base . self::KEY_SUFFIX;
    }
}

有了这个class,下面的代码

$translator = new Translator();
$translator->addTranslation('title', 'This is the default title');
$translator->addTranslation('title', 'This is the homepage title', ['homepage']);

$testString = '{title} - {homepage}';
echo $translator->process($testString, 'random_domain'); // Outputs "This is the default title - {homepage}"
echo '<hr/>';
echo $translator->process($testString, 'homepage');  // Outputs "This is the homepage title - {homepage}"

会输出:

This is the default title - {homepage}<hr/>This is the homepage title - {homepage}