3

I need to dynamically compute my multidimensional array keys for an aggegration in Elasticsearch.

I have the following

$aggs['aggs']['name']

But aggs and name needs to be populated in a loop. So for example:

 $aggs['aggs']['name']['aggs']  = $glue;

// looping

$aggs['aggs']['name']['aggs']['name']['aggs'] = $glue;

// looping

 $aggs['aggs']['name']['aggs']['name']['aggs']['name']['aggs']  = $glue;

// etc

The array keys needs to be computed with the keys aggs and name

How can i dynamically create keys in an array?

Thanks

2
  • 1st iteration adds just aggs? and from 2nd adds [name][aggs]? Commented Jul 6, 2017 at 11:58
  • have a snippet? Because i cannot add the brackets, they needs to be populated Commented Jul 6, 2017 at 12:10

2 Answers 2

10

Hope this is what you want. I have created one array with keys. Then traverse that array to create multi dimension array

$keys = array("aggs","name","aggs","name","aggs");
$aggs = array();

$aggs = add_keys_dynamic($aggs,$keys,"test");
echo "<pre>";
print_r($aggs);

function add_keys_dynamic($main_array, $keys, $value){    
    $tmp_array = &$main_array;
    while( count($keys) > 0 ){        
        $k = array_shift($keys);        
        if(!is_array($tmp_array)){
            $tmp_array = array();
        }
        $tmp_array = &$tmp_array[$k];
    }
    $tmp_array = $value;
    return $main_array;
}

Example

Sign up to request clarification or add additional context in comments.

Comments

-1

use the array_walk_recursive function

<?php
$aggs['aggs']['name'] = "name";

function addEnd(&$item, $key)
{
    if(is_array($item)){
        return;
    }elseif($key=='aggs'){
        $item=['name'=> ['aggs' => $item]];
    }else{
        $item=['aggs' => $item];
    }
}

for($i=0; $i<5; $i++){ // your loop
    array_walk_recursive($aggs, 'addEnd');
}

var_dump($aggs);

check it here: https://3v4l.org/HmlYD

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.